Problem

Example 1:

Solution

Method 1 – Greedy with Prefix Sum

Intuition

To make all prefix sums of the array positive with the minimum number of sign flips, we can greedily flip the most negative numbers encountered so far whenever the prefix sum becomes non-positive. Using a min-heap allows us to efficiently track and flip the largest negative numbers in the prefix.

Approach

  1. Initialize a prefix sum variable and a min-heap to store negative numbers in the prefix.
  2. Iterate through the array, updating the prefix sum.
  3. If the prefix sum becomes non-positive, pop the largest negative number from the heap (i.e., flip its sign), increment the flip count, and update the prefix sum accordingly.
  4. Continue until the end of the array.
  5. Return the minimum number of flips needed.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#include <queue>
class Solution {
public:
    int makePrefSumPositive(vector<int>& nums) {
        int flips = 0, pre = 0;
        priority_queue<int> pq;
        for (int x : nums) {
            pre += x;
            if (x < 0) pq.push(-x);
            while (pre <= 0 && !pq.empty()) {
                pre += 2 * pq.top();
                pq.pop();
                flips++;
            }
        }
        return flips;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import java.util.*;
class Solution {
    public int makePrefSumPositive(int[] nums) {
        int flips = 0, pre = 0;
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        for (int x : nums) {
            pre += x;
            if (x < 0) pq.offer(x);
            while (pre <= 0 && !pq.isEmpty()) {
                int neg = pq.poll();
                pre += -2 * neg;
                flips++;
            }
        }
        return flips;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import heapq
class Solution:
    def makePrefSumPositive(self, nums: list[int]) -> int:
        flips = 0
        pre = 0
        heap = []
        for x in nums:
            pre += x
            if x < 0:
                heapq.heappush(heap, x)
            while pre <= 0 and heap:
                neg = heapq.heappop(heap)
                pre += -2 * neg
                flips += 1
        return flips

Complexity

  • ⏰ Time complexity: O(n log n), as each negative number may be pushed and popped from the heap.
  • 🧺 Space complexity: O(n), for the heap storing negative numbers.