[프로그래머스] 붕대 감기 250137 (JAVA)

dia·2024년 1월 19일
0

구현

방법1

시간 기준, 1초마다 계산

public class NUM250137 {
    public static void main(String[] args) {
        int[] bandage = {5, 1, 5};
        int health = 30;
        int[][] attacks = {{2, 10}, {9, 15}, {10, 5}, {11, 5}};
        System.out.println(solution(bandage, health, attacks));
    }

    public static int solution(int[] bandage, int health, int[][] attacks) {
        int answer = 0;

        int maxHp = health; int time = 0; int count = 0; int nextAtk = 0;
        for(int t = 0; t <= attacks[attacks.length - 1][0]; t++) {
            if(t == attacks[nextAtk][0]) {
                health -= attacks[nextAtk++][1]; count = 0;
                if(health <= 0) { health = -1; break; }
            } else {
                health += bandage[1];
                count++;
                if(count == bandage[0]) { health += bandage[2]; count = 0; }
                if(health > maxHp) { health = maxHp; }
            }
        }

        answer = health;
        return answer;
    }
}

방법2

공격 기준, 공격을 받을 때마다 계산

public class NUM250137 {
    public static void main(String[] args) {
        int[] bandage = {5, 1, 5};
        int health = 30;
        int[][] attacks = {{2, 10}, {9, 15}, {10, 5}, {11, 5}};
        System.out.println(solution(bandage, health, attacks));
    }
    
    public static int solution(int[] bandage, int health, int[][] attacks) {
        int answer = 0;
        answer = health;

        int time = 0;
        for (int[] atk: attacks) {
            if (answer <= 0) { answer = -1;  break; }

            int timeMove = atk[0] - time - 1;
            answer = Math.min(health, answer + (timeMove * bandage[1]));
            answer = Math.min(health, answer + (timeMove / bandage[0] * bandage[2]));
            time = atk[0];

            answer -= atk[1];
        }

        return answer;
    }
}

*다른 분들의 코드를 참고하여 작성했습니다

profile
CS 메모장

0개의 댓글