단순 구현 문제.
예전에는 단순 구현 문제를 더 잘 풀었던 것 같은데, 이제는 어렵게 생각하다보니 자꾸 꼬인다.
어피치가 쏜 화살보다 하나 높여서 쏜 경우와 아예 쏘지 않은 경우로 나눠서 조건에 맞게 구현하면 된다.
import java.util.*;
class Solution {
static int[] ryanBestShot;
static int maxDiff;
public int[] solution(int n, int[] info) {
int[] ryanShot = new int[11];
findBestStrategy(n, info, ryanShot, 0);
return maxDiff != 0 ? ryanBestShot : new int[]{-1};
}
// 최적 전략 찾기
public void findBestStrategy(int arrowsLeft, int[] appeachShot, int[] ryanShot, int idx) {
if(arrowsLeft == 0 || idx == 11) {
if(arrowsLeft > 0) {
ryanShot[10] += arrowsLeft;
}
int scoreDiff = countDiff(appeachShot, ryanShot);
if(scoreDiff > maxDiff || scoreDiff == maxDiff && haveLowerScore(ryanShot, ryanBestShot)) {
maxDiff = scoreDiff;
ryanBestShot = Arrays.copyOf(ryanShot, 11);
}
if(arrowsLeft > 0) {
ryanShot[10] -= arrowsLeft;
}
return;
}
if(appeachShot[idx] < arrowsLeft) {
ryanShot[idx] += appeachShot[idx] + 1;
findBestStrategy(arrowsLeft - (appeachShot[idx] + 1), appeachShot, ryanShot, idx + 1);
ryanShot[idx] = 0;
}
findBestStrategy(arrowsLeft, appeachShot, ryanShot, idx + 1);
}
// 차이 구하기
public int countDiff(int[] appeaches, int[] ryans) {
int appeach = 0;
int ryan = 0;
for(int i = 0; i < 11; i++) {
if(appeaches[i] == 0 && ryans[i] == 0) continue;
if(appeaches[i] >= ryans[i]) appeach += 10 - i;
else if(appeaches[i] < ryans[i]) ryan += 10 - i;
}
return ryan - appeach;
}
// 더 낮은 점수를 많이 맞힌 쪽 구하기
public boolean haveLowerScore(int[] current, int[] best) {
if(best == null) return true;
for(int i = 10; i >= 0; i--) {
if(current[i] > best[i]) return true;
if(best[i] > current[i]) return false;
}
return false;
}
}
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[프로그래머스] 택배 배달과 수거하기 (3) | 2024.10.26 |
---|---|
[프로그래머스] 블록 이동하기 (0) | 2024.10.20 |
[프로그래머스] 합승 택시 요금 (1) | 2024.10.13 |
[프로그래머스] 파괴되지 않은 건물 (1) | 2024.09.30 |
[프로그래머스] 양과 늑대 (0) | 2024.09.15 |