Skip to content

2208. Minimum Operations to Halve Array Sum 👍

  • Time: $O(n\log n + k\log n)$,, k = # of operations
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  int halveArray(vector<int>& nums) {
    const double halfSum = accumulate(nums.begin(), nums.end(), 0.) / 2;
    int ans = 0;
    double runningSum = 0;
    priority_queue<double> maxHeap{nums.begin(), nums.end()};

    while (runningSum < halfSum) {
      const double maxValue = maxHeap.top() / 2;
      runningSum += maxValue, maxHeap.pop();
      maxHeap.push(maxValue);
      ++ans;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public int halveArray(int[] nums) {
    final double halfSum = Arrays.stream(nums).asDoubleStream().sum() / 2;
    int ans = 0;
    double runningSum = 0;
    Queue<Double> maxHeap = new PriorityQueue<>(Collections.reverseOrder());

    for (final double num : nums)
      maxHeap.offer(num);

    while (runningSum < halfSum) {
      final double maxValue = maxHeap.poll() / 2;
      runningSum += maxValue;
      maxHeap.offer(maxValue);
      ++ans;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def halveArray(self, nums: list[int]) -> int:
    halfSum = sum(nums) / 2
    ans = 0
    runningSum = 0.0
    maxHeap = [-num for num in nums]

    heapq.heapify(maxHeap)

    while runningSum < halfSum:
      maxValue = -heapq.heappop(maxHeap) / 2
      runningSum += maxValue
      heapq.heappush(maxHeap, -maxValue)
      ans += 1

    return ans