-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathTakeGiftsFromTheRichestPile.java
More file actions
37 lines (31 loc) · 1017 Bytes
/
TakeGiftsFromTheRichestPile.java
File metadata and controls
37 lines (31 loc) · 1017 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// https://leetcode.com/problems/take-gifts-from-the-richest-pile
// T: O(k * log(N))
// S: O(N)
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
public class TakeGiftsFromTheRichestPile {
public long pickGifts(int[] gifts, int k) {
final Queue<Integer> maxHeap = maHeapFrom(gifts);
for (int i = 0 ; i < k ; i++) {
final int maxPile = maxHeap.poll();
final int giftsToLeaveBehind = (int) Math.max(Math.sqrt(maxPile), 0);
maxHeap.add(giftsToLeaveBehind);
}
return sum(maxHeap);
}
private long sum(Queue<Integer> heap) {
long sum = 0;
while (!heap.isEmpty()) {
sum += heap.poll();
}
return sum;
}
private Queue<Integer> maHeapFrom(int[] array) {
final Queue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
for (int element : array) {
maxHeap.add(element);
}
return maxHeap;
}
}