본문 바로가기
Dev/Algorithm

[프로그래머스] 붕대 감기

by VIPeveloper 2024. 5. 17.
반응형

문제

https://school.programmers.co.kr/learn/courses/30/lessons/250137

 

프로그래머스

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

programmers.co.kr

생각

  • 마지막 공격 받은 시점까지 순회하면서
    • 공격을 안받았다면 : 연속 성공 시간 증가, 체력 증가, 최대 체력 관리,
    • 공격 받았다면 : 연속 성공 시간 초기화, 체력 감소, 공격 idx 증가, 죽음 관리

더 고려할 생각

  • 연속 성공 최대 시 다시 0 으로가는걸 고려 못함.
  • 예제 코드를 더 잘 보자.

코드

public class Main {
    public static void main(String[] args) {
        System.out.println(solution(new int[]{5, 1, 5}, 30, new int[][]{{2, 10}, {9, 15}, {10, 5}, {11, 5}}));
        System.out.println(solution(new int[]{3,2,7}, 20, new int[][]{{1, 15}, {5, 16}, {8, 6}}));
        System.out.println(solution(new int[]{4,2, 7}, 20, new int[][]{{1, 15}, {5, 16}, {8, 6}}));
        System.out.println(solution(new int[]{1,1,1}, 5, new int[][]{{1, 2}, {3, 2}}));
    }
    public static int solution(int[] bandage, int health, int[][] attacks) {
        int healIdx = 0;
        int attackIdx = 0;
        int max_health = health;

        for (int i = 1; i <= attacks[attacks.length-1][0]; i++) {
            if(i==attacks[attackIdx][0]){
                // 공격을 받은 경우
                healIdx = 0;  // 초기화
                health -= attacks[attackIdx++][1];  // 체력 감소
                if(health<=0) return -1;    // 죽음 관리
            }else{
                // 공격받지 않은 경우
                healIdx++;
                health += bandage[1];
                if(healIdx == bandage[0]) {
                    health += bandage[2];
                    healIdx = 0;
                }
                if(health > max_health) health = max_health;
            }
        }
        return health;
    }
}

 

다른 사람 코드

  • 시간차이와 추가 체력을 계산한 것이 다른점이다. 
public class Main {
    public static void main(String[] args) {
        System.out.println(solution(new int[]{5, 1, 5}, 30, new int[][]{{2, 10}, {9, 15}, {10, 5}, {11, 5}}));
        System.out.println(solution(new int[]{3,2,7}, 20, new int[][]{{1, 15}, {5, 16}, {8, 6}}));
        System.out.println(solution(new int[]{4,2, 7}, 20, new int[][]{{1, 15}, {5, 16}, {8, 6}}));
        System.out.println(solution(new int[]{1,1,1}, 5, new int[][]{{1, 2}, {3, 2}}));
    }
    public static int solution(int[] bandage, int health, int[][] attacks) {
        int cnt = bandage[0]; // 추가 체력 기준
        int now = health; // 현재 체력
        int std = 0; // 마지막으로 공격당한 시간

        int v1, v2; // 추가 체력 받을 수 있나?
        for (int[] atk: attacks) {
            if (now <= 0) {
                return -1;
            }

            v1 = atk[0] - std - 1; // 시간 차이
            v2 = v1 / cnt; // 추가 체력 회수

            // 맞기 직전까지의 체력 정산
            std = atk[0];
            now = Math.min(health, now + (v1 * bandage[1]));
            now = Math.min(health, now + (v2 * bandage[2]));

            now -= atk[1];
        }

        return now <= 0 ? -1 : now;
    }
}

 

 

 

반응형