



나의 풀이
class Solution {
public int solution(int[] bandage, int health, int[][] attacks) {
int answer = 0;
int hp = health; // 1
int count = 0;
int time = 0;
for (int i = 1; i <= attacks[attacks.length - 1][0]; i++) { // 2
if (i != attacks[count][0]) { // 3
hp += bandage[1];
time++;
if (time == bandage[0]) { // 4
hp += bandage[2];
time = 0;
}
if (hp > health) hp = health; // 5
} else { // 6
hp -= attacks[count++][1];
time = 0;
if (hp <= 0) return answer = -1;
}
}
return answer = hp;
}
}
과정
- 현재 체력을 저장할 hp, 공격의 번째를 카운트할 count, 연속으로 회복한 횟수를 저장할 time을 선언
- attacks의 마지막 배열의 시간까지 순회하는 반복문을 선언
- 현재 시간이 attacks의 공격 시간이 아닐경우 bandage의 초당 회복량만큼 회복, 연속 회복 횟수 증가
- 만약 연속 회복 횟수가 bandage의 시전 시간과 같을 경우 추가 회복량만큼 추가 회복, 연속 회복 횟수 초기화
- 만약 현재 체력이 최대 체력을 넘어설경우 현재 체력을 최대 체력으로 초기화
- 현재 시간이 attacks의 공격 시간일 경우 attacks의 순서대로 hp 감소, 연속 회복 횟수 초기화, 만약 hp가 0 이하로 떨어질 경우 -1을 리턴, 아니면 남은 hp 리턴
다른 사람 풀이
import java.util.*;
class Solution {
public 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;
}
}