본문 바로가기
알고리즘/프로그래머스

[프로그래머스] 양궁 대회

by hwan-da 2024. 9. 23.

단순 구현 문제.

예전에는 단순 구현 문제를 더 잘 풀었던 것 같은데, 이제는 어렵게 생각하다보니 자꾸 꼬인다.

 

어피치가 쏜 화살보다 하나 높여서 쏜 경우와 아예 쏘지 않은 경우로 나눠서 조건에 맞게 구현하면 된다.

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;
    }
}