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.
Initialize a prefix sum variable and a min-heap to store negative numbers in the prefix.
Iterate through the array, updating the prefix sum.
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.
#include<queue>classSolution {
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.*;
classSolution {
publicintmakePrefSumPositive(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
classSolution:
defmakePrefSumPositive(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 <=0and heap:
neg = heapq.heappop(heap)
pre +=-2* neg
flips +=1return flips