Skip to content

Commit 3d6a4bb

Browse files
committed
Sync LeetCode submission Runtime - 26 ms (96.34%), Memory - 34.2 MB (62.20%)
1 parent a7fb607 commit 3d6a4bb

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. You can apply the following operation any number of times:</p>
2+
3+
<ul>
4+
<li>Pick any element from <code>nums</code> and put it at the end of <code>nums</code>.</li>
5+
</ul>
6+
7+
<p>The prefix sum array of <code>nums</code> is an array <code>prefix</code> of the same length as <code>nums</code> such that <code>prefix[i]</code> is the sum of all the integers <code>nums[j]</code> where <code>j</code> is in the inclusive range <code>[0, i]</code>.</p>
8+
9+
<p>Return <em>the minimum number of operations such that the prefix sum array does not contain negative integers</em>. The test cases are generated such that it is always possible to make the prefix sum array non-negative.</p>
10+
11+
<p>&nbsp;</p>
12+
<p><strong class="example">Example 1:</strong></p>
13+
14+
<pre>
15+
<strong>Input:</strong> nums = [2,3,-5,4]
16+
<strong>Output:</strong> 0
17+
<strong>Explanation:</strong> we do not need to do any operations.
18+
The array is [2,3,-5,4]. The prefix sum array is [2, 5, 0, 4].
19+
</pre>
20+
21+
<p><strong class="example">Example 2:</strong></p>
22+
23+
<pre>
24+
<strong>Input:</strong> nums = [3,-5,-2,6]
25+
<strong>Output:</strong> 1
26+
<strong>Explanation:</strong> we can do one operation on index 1.
27+
The array after the operation is [3,-2,6,-5]. The prefix sum array is [3, 1, 7, 2].
28+
</pre>
29+
30+
<p>&nbsp;</p>
31+
<p><strong>Constraints:</strong></p>
32+
33+
<ul>
34+
<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
35+
<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>
36+
</ul>
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# Approach: Greedy
2+
3+
# Time: O(n log n)
4+
# Space: O(n)
5+
6+
import heapq
7+
8+
class Solution:
9+
def makePrefSumNonNegative(self, nums: List[int]) -> int:
10+
operations = 0
11+
prefix_sum = 0
12+
pq = []
13+
14+
for num in nums:
15+
# Push negative numbers to min heap
16+
if num < 0:
17+
heapq.heappush(pq, num)
18+
19+
prefix_sum += num
20+
21+
# Pop minimum element from heap and subtract from sum
22+
if prefix_sum < 0:
23+
prefix_sum -= heapq.heappop(pq)
24+
operations += 1
25+
26+
return operations

0 commit comments

Comments
 (0)