Skip to content

Commit 52e3dcf

Browse files
authored
Create maximum-alternating-subarray-sum.py
1 parent 7b3c17b commit 52e3dcf

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# Time: O(n)
2+
# Space: O(1)
3+
4+
class Solution(object):
5+
def maximumAlternatingSubarraySum(self, nums):
6+
"""
7+
:type nums: List[int]
8+
:rtype: int
9+
"""
10+
def kadane(nums, start):
11+
result = float("-inf")
12+
curr = odd = 0
13+
for i in xrange(start, len(nums)):
14+
curr = (curr+nums[i]) if not odd else max(curr-nums[i], 0)
15+
result = max(result, curr)
16+
odd ^= 1
17+
return result
18+
19+
return max(kadane(nums, 0), kadane(nums, 1))

0 commit comments

Comments
 (0)