본문 바로가기

코딩 테스트/프로그래머스

프로그래머스 라면공장 Java 풀이

기존 풀이

import java.util.*;

public class Solution {

    public static <integer> int solution(int stock, int[] dates, int[] supplies, int k) {
        int answer = 0;
        Queue<Integer> priorityQueue = new PriorityQueue<Integer>(Comparator.reverseOrder());

        int index = 0;
        for (int i = 0; i < k; i++) {
            if(index < dates.length && i == dates[index])
                priorityQueue.add(supplies[index++]);

            if(stock == 0) {
                stock += priorityQueue.poll();
                answer++;
            }
            stock--;
        }
        return answer;
    }
}

https://lkhlkh23.tistory.com/113 이 분의 풀이이다.

 

다른 사람의 풀이

import java.util.Comparator;
import java.util.PriorityQueue;

class Solution {
    public int solution(int stock, int[] dates, int[] supplies, int k) {
        PriorityQueue<Integer> pqSupplies = new PriorityQueue<>(new Comparator<Integer>() {

            @Override
            public int compare(Integer o1, Integer o2) {
                return o2 - o1;
            }
        });

        int spIdx = 0;
        int cnt = 0;
        for (int day=0; day<k; day++) {
            if (spIdx < dates.length && day >= dates[spIdx]) {
                pqSupplies.add(supplies[spIdx]);
                spIdx++;
            }
            if (stock <= 0) {
                stock += pqSupplies.remove();
                cnt++;
            }

            stock--;
        }

        return cnt;
    }
}