Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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.
Example 1:
Input: nums = [5,19,8,1] Output: 3 Explanation: The initial sum of nums is equal to 5 + 19 + 8 + 1 = 33. The following is one of the ways to reduce the sum by at least half: Pick the number 19 and reduce it to 9.5. Pick the number 9.5 and reduce it to 4.75. Pick the number 8 and reduce it to 4. The final array is [5, 4.75, 4, 1] with a total sum of 5 + 4.75 + 4 + 1 = 14.75. The sum of nums has been reduced by 33 - 14.75 = 18.25, which is at least half of the initial sum, 18.25 >= 33/2 = 16.5. Overall, 3 operations were used so we return 3. It can be shown that we cannot reduce the sum by at least half in less than 3 operations.
Example 2:
Input: nums = [3,8,20] Output: 3 Explanation: The initial sum of nums is equal to 3 + 8 + 20 = 31. The following is one of the ways to reduce the sum by at least half: Pick the number 20 and reduce it to 10. Pick the number 10 and reduce it to 5. Pick the number 3 and reduce it to 1.5. The final array is [1.5, 8, 5] with a total sum of 1.5 + 8 + 5 = 14.5. The sum of nums has been reduced by 31 - 14.5 = 16.5, which is at least half of the initial sum, 16.5 >= 31/2 = 15.5. Overall, 3 operations were used so we return 3. It can be shown that we cannot reduce the sum by at least half in less than 3 operations.
Constraints:
1 <= nums.length <= 1051 <= nums[i] <= 107Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Greedy
[5,19,8,1]
[3,8,20]
remove-stones-to-minimize-the-total)minimum-operations-to-exceed-threshold-value-ii)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2208: Minimum Operations to Halve Array Sum
class Solution {
public int halveArray(int[] nums) {
PriorityQueue<Double> pq = new PriorityQueue<>(Collections.reverseOrder());
double s = 0;
for (int x : nums) {
s += x;
pq.offer((double) x);
}
s /= 2.0;
int ans = 0;
while (s > 0) {
double t = pq.poll() / 2.0;
s -= t;
pq.offer(t);
++ans;
}
return ans;
}
}
// Accepted solution for LeetCode #2208: Minimum Operations to Halve Array Sum
func halveArray(nums []int) (ans int) {
var s float64
pq := &hp{}
for _, x := range nums {
s += float64(x)
heap.Push(pq, float64(x))
}
s /= 2
for s > 0 {
t := heap.Pop(pq).(float64) / 2
s -= t
ans++
heap.Push(pq, t)
}
return
}
type hp struct{ sort.Float64Slice }
func (h hp) Less(i, j int) bool { return h.Float64Slice[i] > h.Float64Slice[j] }
func (h *hp) Push(v any) { h.Float64Slice = append(h.Float64Slice, v.(float64)) }
func (h *hp) Pop() any {
a := h.Float64Slice
v := a[len(a)-1]
h.Float64Slice = a[:len(a)-1]
return v
}
# Accepted solution for LeetCode #2208: Minimum Operations to Halve Array Sum
class Solution:
def halveArray(self, nums: List[int]) -> int:
s = sum(nums) / 2
pq = []
for x in nums:
heappush(pq, -x)
ans = 0
while s > 0:
t = -heappop(pq) / 2
s -= t
heappush(pq, -t)
ans += 1
return ans
// Accepted solution for LeetCode #2208: Minimum Operations to Halve Array Sum
use std::collections::BinaryHeap;
impl Solution {
pub fn halve_array(nums: Vec<i32>) -> i32 {
let mut pq: BinaryHeap<i64> = BinaryHeap::new();
let mut s: i64 = 0;
for x in nums {
let v = (x as i64) << 20;
s += v;
pq.push(v);
}
s /= 2;
let mut ans = 0;
while s > 0 {
let t = pq.pop().unwrap() / 2;
s -= t;
pq.push(t);
ans += 1;
}
ans
}
}
// Accepted solution for LeetCode #2208: Minimum Operations to Halve Array Sum
function halveArray(nums: number[]): number {
let s: number = nums.reduce((a, b) => a + b) / 2;
const pq = new MaxPriorityQueue<number>();
for (const x of nums) {
pq.enqueue(x);
}
let ans = 0;
while (s > 0) {
const t = pq.dequeue() / 2;
s -= t;
++ans;
pq.enqueue(t);
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.
Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.