Algorithm/Programmers

[Programmers] [PCCP 기출문제] 1번 / 붕대 감기 / ⭕

cks._.hong 2024. 6. 30. 23:26
 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

1. 제출 코드

class Solution {
    public int solution(int[] bandage, int health, int[][] attacks) {
        int answer = health;
        int length = attacks.length - 1;
        int sec = 1;
        int idx = 0;
        int skill = 0;
        
        // 몬스터의 마지막 공격 시간까지
        while(sec <= attacks[length][0]) {
            // 몬스터가 공격할 때
            if(attacks[idx][0] == sec) {
                skill = 0;
                int temp = answer - attacks[idx][1];
                // 공격을 받고 체력이 0 이하가 되면 -1
                if(temp <= 0) {
                    return -1;
                }
                answer = temp;
                idx++;
            } else {
                skill++;
                int temp = answer + bandage[1];
                // 최대 체력을 넘어가지 않게
                if(temp > health) {
                    answer = health;
                } else {
                    answer = temp;
                }
                // t초 연속으로 붕대를 감는 경우 추가 체력 회복
                if(skill % bandage[0] == 0) {
                    int tmp = answer + bandage[2];
                    if(tmp > health) {
                        answer = health;
                    } else {
                        answer = tmp;
                    }
                }
            }
            sec++;
        }
        return answer;
    }
}

 

2. 개선 코드

class Solution {
    public int solution(int[] bandage, int health, int[][] attacks) {
        int answer = health;
        int length = attacks.length - 1;
        int sec = 1;
        int idx = 0;
        int skill = 0;
        
        // 몬스터의 마지막 공격 시간까지
        while(sec <= attacks[length][0]) {
            // 몬스터가 공격할 때
            if(attacks[idx][0] == sec) {
                skill = 0;
                int temp = answer - attacks[idx][1];
                // 공격을 받고 체력이 0 이하가 되면 -1
                if(temp <= 0) {
                    return -1;
                }
                answer = temp;
                idx++;
            } else {
                skill++;
                // 최대 체력을 넘어가지 않게
                answer = calc_health(answer, bandage[1], health);
                // t초 연속으로 붕대를 감는 경우 추가 체력 회복
                if(skill % bandage[0] == 0) {
                    answer = calc_health(answer, bandage[2], health);
                }
            }
            sec++;
        }
        return answer;
    }
    
    // 체력 계산기
    static int calc_health(int health, int number, int maxValue) {
        int temp = health + number;
        if(temp > maxValue) {
            return maxValue;
        } else {
            return temp;
        }
    }
}
  • 체력을 계산하는 과정에서 코드의 중복이 발생하는 것을 함수로 따로 빼서 코드를 작성해봤다.

 

3. 유의할 점

  • 공격을 받고 체력이 0이하가 되면 0으로 다시 초기화하고 다음 과정(체력 회복)이 진행되는 것이 아니라 종료되야함