
You are given a 0-indexed integer array nums and an integer k. You have a starting score of 0.
In one operation:
choose an index i such that 0 <= i < nums.length,
increase your score by nums[i], and
replace nums[i] with ceil(nums[i] / 3).
Return the maximum possible score you can attain after applying exactly k operations.
The ceiling function ceil(val) is the least integer greater than or equal to val.
1 <= nums.length, k <= 10^5
1 <= nums[i] <= 10^9
$$ 시간복잡도=O(n log n + k log n)$$
add(), offer(), poll())이 이뤄져도 충분한데, 자꾸 int[]에 연산 결과를 반영하려함. (Array.asList() 같은 방법 사용 시도)new PriorityQueue<>(Comparator.reverseOrder())int / 3 == int과 int / 3.0 == double의 차이를 망각. 결과적으로 문제가 제시한 ceil()의 제대로된 리턴값 생성 실패.// 문제 해결 이후.
class Solution {
public static long maxKelements(int[] nums, int k) {
long score = 0;
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
for (int num: nums)
maxHeap.offer(num);
for (int i = 0; i < k; i++) {
int max = maxHeap.poll();
score += max;
maxHeap.offer((int) (Math.ceil(max / 3.0)));
}
return score;
}
}
ceil() 대신 (v + 2) / 3을 활용해 연산 단축.class Solution {
public long maxKelements(int[] nums, int k) {
PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> b - a);
for (int v : nums) {
pq.offer(v);
}
long score = 0;
while (k-- > 0) {
int v = pq.poll();
score += v;
pq.offer((v + 2) / 3);
}
return score;
}
}