Remove Stones to Minimize the Total

medium heap greedy

Problem

On each of k operations, choose a pile and remove floor(pile/2) stones. Minimize the final total.

Inputpiles = [5,4,9], k = 2
Output12
9 → 5; 5 → 3 (other 5); total = 5 + 3 + 4 = 12.

import heapq
def min_stone_sum(piles, k):
    heap = [-p for p in piles]
    heapq.heapify(heap)
    for _ in range(k):
        x = -heapq.heappop(heap)
        x -= x // 2
        heapq.heappush(heap, -x)
    return -sum(heap)
function minStoneSum(piles, k) {
  // simple sort-based heap simulation for clarity
  piles = piles.slice();
  for (let i = 0; i < k; i++) {
    piles.sort((a, b) => b - a);
    piles[0] -= Math.floor(piles[0] / 2);
  }
  return piles.reduce((a, b) => a + b, 0);
}
class Solution {
    public int minStoneSum(int[] piles, int k) {
        PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
        for (int p : piles) pq.offer(p);
        for (int i = 0; i < k; i++) {
            int x = pq.poll();
            x -= x / 2;
            pq.offer(x);
        }
        int sum = 0; for (int x : pq) sum += x; return sum;
    }
}
int minStoneSum(vector<int>& piles, int k) {
    priority_queue<int> pq(piles.begin(), piles.end());
    for (int i = 0; i < k; i++) {
        int x = pq.top(); pq.pop();
        x -= x / 2;
        pq.push(x);
    }
    int sum = 0; while (!pq.empty()) { sum += pq.top(); pq.pop(); } return sum;
}
Time: O(k log n) Space: O(n)