Remove Stones to Minimize the Total - Problem

You are given a 0-indexed integer array piles, where piles[i] represents the number of stones in the ith pile, and an integer k. You should apply the following operation exactly k times:

Choose any piles[i] and remove floor(piles[i] / 2) stones from it.

Notice that you can apply the operation on the same pile more than once.

Return the minimum possible total number of stones remaining after applying the k operations.

floor(x) is the largest integer that is smaller than or equal to x (i.e., rounds x down).

Input & Output

Example 1 — Basic Case
$ Input: piles = [5,4,9], k = 2
Output: 12
💡 Note: Operation 1: Remove floor(9/2) = 4 stones from pile with 9 stones, leaving [5,4,5]. Operation 2: Remove floor(5/2) = 2 stones from any pile with 5 stones, leaving [5,2,5] or [3,4,5]. Total remaining = 12.
Example 2 — Single Operation
$ Input: piles = [4,3,6,7], k = 1
Output: 17
💡 Note: Remove floor(7/2) = 3 stones from the largest pile (7), leaving [4,3,6,4]. Total remaining = 4 + 3 + 6 + 4 = 17.
Example 3 — Multiple Operations on Same Pile
$ Input: piles = [20], k = 3
Output: 3
💡 Note: Operation 1: 20 → 10 (remove 10). Operation 2: 10 → 5 (remove 5). Operation 3: 5 → 3 (remove 2). Final result = 3.

Constraints

  • 1 ≤ piles.length ≤ 105
  • 1 ≤ piles[i] ≤ 104
  • 1 ≤ k ≤ 105

Visualization

Tap to expand
Remove Stones to Minimize the Total INPUT piles array visualization: pile[0] 5 pile[1] 4 pile[2] 9 piles = [5, 4, 9] k = 2 Total: 5+4+9 = 18 5 4 9 Index: 0, 1, 2 ALGORITHM STEPS 1 Build Max Heap Sort: largest first MaxHeap: [9, 5, 4] 9 is at top (largest) 2 Operation 1 (k=1) Remove floor(9/2)=4 9 - 4 = 5 Heap: [5, 5, 4] 3 Operation 2 (k=2) Remove floor(5/2)=2 5 - 2 = 3 Heap: [5, 3, 4] 4 Sum Remaining k=0, calculate total 5 + 3 + 4 = 12 FINAL RESULT Final piles after k=2 ops: pile[0] 5 pile[1] 4 pile[2] 3 (unchanged) (unchanged) (was 9) OUTPUT 12 OK - Verified! 5 + 4 + 3 = 12 Key Insight: Use a Max Heap to always remove stones from the largest pile. Greedy approach works because floor(x/2) removes more stones from larger piles. After k operations, sum all remaining stones. Time: O(n + k*log(n)) | Space: O(n) for the heap TutorialsPoint - Remove Stones to Minimize the Total | Greedy with Sorting (Max Heap)
Asked in
Amazon 45 Google 38 Microsoft 32 Facebook 28
89.5K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen