문제
https://school.programmers.co.kr/learn/courses/30/lessons/12927
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
풀이
PriorityQueue를 이용하여 풀이를 했다
간단하게 가장 큰 수의 값을 줄이면 되기 때문에 PriorityQueue를 이용하여 가장 큰 값을 줄여준다
줄인 값이 0이 되면 que안에 넣지 않는다
코드
import java.util.*;
class Solution {
public long solution(int n, int[] works) {
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
for(int i=0;i<works.length;i++){
pq.add(works[i]);
}
for(int i=0;i<n;i++){
if(pq.isEmpty()) break;
int max = pq.poll();
max = max - 1;
if(max != 0) pq.add(max);
}
long answer = 0;
for(int i=0;i<works.length;i++){
if(pq.isEmpty()) break;
int item = pq.poll();
answer += item*item;
}
System.out.println(answer);
return answer;
}
}
cf) 배열을 이용하여 접근할 경우