본문 바로가기
알고리즘 문제/Java

[프로그래머스/Java] 광물 캐기

by 현장 2026. 5. 5.

-Code

import java.util.*;

class Solution {
    static class Minerals {
        int diamondCnt, ironCnt, stoneCnt;

        public Minerals() {
            this.diamondCnt = 0;
            this.ironCnt = 0;
            this.stoneCnt = 0;
        }

        public void add(String type) {
            if (type.equals("diamond")) diamondCnt++;
            else if (type.equals("iron")) ironCnt++;
            else stoneCnt++;
        }
    }

    public int solution(int[] picks, String[] minerals) {
        // 총 곡괭이 수
        int totalPicks = picks[0] + picks[1] + picks[2];
        // 광물을 곡괭이 단위로 묶기
        List<Minerals> mineralList = new ArrayList<>();
        for (int i = 0; i < Math.min(minerals.length, totalPicks * 5); i += 5) {
            Minerals now = new Minerals();
            for (int j = i; j < Math.min(i + 5, minerals.length); j++) {
                now.add(minerals[j]); // minerals[idx] 대신 루프 변수 사용 주의!
            }
            mineralList.add(now);
        }
        // 다이아, 철, 돌 순으로 정렬
        mineralList.sort((o1, o2) -> {
            // 다이아 내림차순
            if (o1.diamondCnt != o2.diamondCnt) {
                return o2.diamondCnt - o1.diamondCnt;
            }
            // 철 내림차순
            if (o1.ironCnt != o2.ironCnt) {
                return o2.ironCnt - o1.ironCnt;
            }
            // 돌 내림차순
            return o2.stoneCnt - o1.stoneCnt;
        });
        // 피로도 계산
        int fatigue = 0;
        for (Minerals m : mineralList) {
            if (picks[0] > 0) {
                // 다이아 곡괭이가 있는 경우
                fatigue += m.diamondCnt + m.ironCnt + m.stoneCnt;
                picks[0]--;
            } else if (picks[1] > 0) {
                // 철 곡괭이가 있는 경우
                fatigue += m.diamondCnt * 5 + m.ironCnt + m.stoneCnt;
                picks[1]--;
            } else if (picks[2] > 0){
                // 돌 곡괭이가 있는 경우
                fatigue += m.diamondCnt * 25 + m.ironCnt * 5 + m.stoneCnt;
                picks[2]--;
            } 
        }
        return fatigue;
    }
}

처음에 그리디 방식으로 짜려다 잘 안 풀려서 찾아보니 곡괭이 단위로 묶어서 처리해야 한다는 힌트를 보고 로직을 다시 짜서 해결했습니다.