-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0862-shortest-subarray-with-sum-at-least-k.py
More file actions
39 lines (34 loc) · 1.09 KB
/
0862-shortest-subarray-with-sum-at-least-k.py
File metadata and controls
39 lines (34 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# time complexity: O(nlogn)
# space complexity: O(n)
from heapq import heappop, heappush
from typing import List
class Solution:
def shortestSubarray(self, nums: List[int], k: int) -> int:
shortestSubarrayLength = float("inf")
cumulativeSum = 0
prefixSumHeap = []
for i, num in enumerate(nums):
cumulativeSum += num
if cumulativeSum >= k:
shortestSubarrayLength = min(shortestSubarrayLength, i + 1)
while (
prefixSumHeap and cumulativeSum - prefixSumHeap[0][0] >= k
):
shortestSubarrayLength = min(
shortestSubarrayLength, i - heappop(prefixSumHeap)[1]
)
heappush(prefixSumHeap, (cumulativeSum, i))
return (
-1
if shortestSubarrayLength == float("inf")
else shortestSubarrayLength
)
nums = [1]
k = 1
print(Solution().shortestSubarray(nums, k))
nums = [1, 2]
k = 4
print(Solution().shortestSubarray(nums, k))
nums = [2, -1, 2]
k = 3
print(Solution().shortestSubarray(nums, k))