Untitled
unknown
plain_text
9 months ago
1.2 kB
5
Indexable
import java.util.PriorityQueue;
public class MinStoneSum {
public int minStoneSum(int[] piles, int k) {
// Max-heap for the piles (using negative values for max-heap behavior)
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a);
// Add all piles to the heap
for (int pile : piles) {
maxHeap.offer(pile);
}
// Perform k operations
while (k-- > 0 && !maxHeap.isEmpty()) {
int largest = maxHeap.poll();
int reduced = largest - largest / 2;
maxHeap.offer(reduced);
}
// Sum up the remaining stones
int totalStones = 0;
while (!maxHeap.isEmpty()) {
totalStones += maxHeap.poll();
}
return totalStones;
}
public static void main(String[] args) {
MinStoneSum solver = new MinStoneSum();
int[] piles1 = {5, 4, 9};
int k1 = 2;
System.out.println(solver.minStoneSum(piles1, k1)); // Output: 12
int[] piles2 = {4, 3, 6, 7};
int k2 = 3;
System.out.println(solver.minStoneSum(piles2, k2)); // Output: 12
}
}
Editor is loading...
Leave a Comment