Skip to content

Commit e94aef8

Browse files
authored
Create maximum-good-subarray-sum.py
1 parent 18652a6 commit e94aef8

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

Python/maximum-good-subarray-sum.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Time: O(n)
2+
# Space: O(n)
3+
4+
import collections
5+
6+
7+
# prefix sum
8+
class Solution(object):
9+
def maximumSubarraySum(self, nums, k):
10+
"""
11+
:type nums: List[int]
12+
:type k: int
13+
:rtype: int
14+
"""
15+
prefix = collections.defaultdict(lambda: float("inf"))
16+
curr = 0
17+
result = float("-inf")
18+
for x in nums:
19+
prefix[x] = min(prefix[x], curr)
20+
curr += x
21+
result = max(result, curr-prefix[x-k], curr-prefix[x+k])
22+
return result if result != float("-inf") else 0

0 commit comments

Comments
 (0)