Minimum Operations to Halve Array Sum - Problem

You are given an array nums of positive integers. In one operation, you can choose any number from nums and reduce it to exactly half the number. (Note that you may choose this reduced number in future operations.)

Return the minimum number of operations to reduce the sum of nums by at least half.

Input & Output

Example 1 — Basic Case
$ Input: nums = [5,19,8,1]
Output: 3
💡 Note: Original sum = 33, target reduction ≥ 16.5. Operations: halve 19→9.5 (reduction=9.5), halve 9.5→4.75 (total=14.25), halve 8→4 (total=18.25≥16.5). Answer: 3 operations.
Example 2 — Small Array
$ Input: nums = [3,8,20]
Output: 3
💡 Note: Original sum = 31, target reduction ≥ 15.5. Operations: halve 20→10 (reduction=10), halve 10→5 (total=15), halve 8→4 (total=19≥15.5). Answer: 3 operations.
Example 3 — Edge Case
$ Input: nums = [1,1]
Output: 2
💡 Note: Original sum = 2, target reduction ≥ 1. Operations: halve 1→0.5 (reduction=0.5), halve 1→0.5 (total=1≥1). Answer: 2 operations.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 107

Visualization

Tap to expand
Minimum Operations to Halve Array Sum INPUT nums = [5, 19, 8, 1] 5 19 8 1 [0] [1] [2] [3] Total Sum = 5+19+8+1 = 33 Target = 33/2 = 16.5 Reduce sum by at least 16.5 Max Heap (sorted) 19 8 5 1 ALGORITHM STEPS 1 Halve 19 --> 9.5 Sum: 33-9.5 = 23.5 Reduced: 9.5 (need 16.5) 2 Halve 9.5 --> 4.75 Sum: 23.5-4.75 = 18.75 Reduced: 14.25 (need 16.5) 3 Halve 8 --> 4 Sum: 18.75-4 = 14.75 Reduced: 18.25 >= 16.5 4 Done! Target reached Operations = 3 Heap State After Each Op Op1: [9.5, 8, 5, 1] Op2: [8, 5, 4.75, 1] Op3: [5, 4.75, 4, 1] Final sum: 14.75 (OK) FINAL RESULT Output 3 3 operations needed to halve the sum Summary Original sum: 33 Target reduction: 16.5 Actual reduction: 18.25 Final sum: 14.75 14.75 <= 16.5 -- OK Key Insight: Greedy approach: Always halve the largest number! Using a max-heap ensures we always pick the maximum value. Halving the largest gives the biggest reduction per operation, minimizing total operations. Time: O(n log n), Space: O(n) for the heap. TutorialsPoint - Minimum Operations to Halve Array Sum | Greedy with Sorting
Asked in
Amazon 35 Google 28 Microsoft 22 Meta 15
32.1K Views
Medium Frequency
~25 min Avg. Time
856 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