본문 바로가기
Portpolio/codingtest

프로그래머스 Lv3. 야근 지수 풀이

by Peter Choi 2025. 3. 21.
반응형

https://school.programmers.co.kr/learn/courses/30/lessons/12927

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

 

자바

import java.util.PriorityQueue;
import java.util.Collections;

class Solution {
    public long solution(int n, int[] works) {
        long answer = 0;
        
        PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
        
        for(int work:works)
        {
            pq.offer(work);
        }
        
        for(int i = 0; i < n; i++)
        {

            //이렇게 if 처리 안하면 런타임 에러 발생
            if(!pq.isEmpty())
            {
                int max = pq.poll();
            
                if(max > 0)
                {
                    max-=1;        
                    pq.offer(max);
                }
            }
            
            else
            {
                break;
            }
        }
        
        while(!pq.isEmpty())
        {
            int yageun = pq.poll();
            answer += (long) yageun * yageun;
        }
        
        return answer;
    }
}

반응형

댓글