Skip to content

Commit c9105b9

Browse files
authored
Create maximum-subarray-sum-with-length-divisible-by-k.py
1 parent a2d0fb7 commit c9105b9

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Time: O(n)
2+
# Space: O(k)
3+
4+
# prefix sum, dp
5+
class Solution(object):
6+
def maxSubarraySum(self, nums, k):
7+
"""
8+
:type nums: List[int]
9+
:type k: int
10+
:rtype: int
11+
"""
12+
dp = [float("inf")]*k
13+
dp[-1] = 0
14+
curr = 0
15+
result = float("-inf")
16+
for i, x in enumerate(nums):
17+
curr += x
18+
result = max(result, curr-dp[i%k])
19+
dp[i%k] = min(dp[i%k], curr)
20+
return result

0 commit comments

Comments
 (0)