
내가 작성한 코드
import java.util.*;
class Solution {
public int solution(int[] bandage, int health, int[][] attacks) {
int answer = health; // 현재 체력 초기화
Map<Integer, Integer> attackMap = new HashMap<>(); // 공격 시간과 공격력을 저장하는 맵
int cating = bandage[0]; // 치유 시간
int healPerSecond = bandage[1]; // 초당 치유량
int bonusHeal = bandage[2] + healPerSecond; // 보너스 치유
int healChain = 0; // 연속 치유 횟수
int totalTime = attacks[attacks.length - 1][0]; // 마지막 공격 시간
// 공격 시간과 공격력을 맵에 저장
for (int[] attack : attacks) {
int time = attack[0]; // 공격 시간
int damage = attack[1]; // 공격력
attackMap.put(time, attackMap.getOrDefault(time, 0) + damage);
}
for (int i = 1; i <= totalTime; i++) {
if (attackMap.containsKey(i)) {
// 현재 시간에 공격이 있다면 체력 감소
answer -= attackMap.get(i);
healChain = 0; // 연속 치유 횟수 초기화
// 체력이 0 이하가 되면 종료
if (answer <= 0) {
return -1;
}
} else {
// 현재 시간에 공격이 없다면 치유
healChain++;
if (healChain < cating) {
// 치유 중
answer += healPerSecond;
} else {
// 치유가 끝나면 보너스 치유 적용
answer += bonusHeal;
healChain = 0; // 연속 치유 횟수 초기화
}
// 체력이 최대치를 초과하지 않도록 조정
if (answer > health) {
answer = health;
}
}
}
return answer; // 체력이 0 이하가 되면 -1 반환
}
}
다른 사람의 코드
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;
}
}
Share article