Skip to content

Commit 37d7287

Browse files
committed
Runtime: 729 ms (Top 66.43%) | Memory: 18.9 MB (Top 76.46%)
1 parent 5bd40ff commit 37d7287

File tree

1 file changed

+17
-23
lines changed

1 file changed

+17
-23
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,43 @@
1+
# Runtime: 729 ms (Top 66.43%) | Memory: 18.9 MB (Top 76.46%)
12
class Solution:
2-
3+
34
def kadanes(self,nums):
4-
5+
56
#kadanes algo
6-
7+
78
max_till_now = nums[0]
89
curr_max = nums[0]
9-
10+
1011
for i in range(1,len(nums)):
1112
curr_max = max(curr_max+nums[i],nums[i])
1213
max_till_now = max(max_till_now,curr_max)
13-
14+
1415
return max_till_now
15-
16-
16+
1717
def maxSubarraySumCircular(self, nums: List[int]) -> int:
18-
18+
1919
#there will be 2 case
2020
#case 1 : our max subarray is not wrapping i.e not circular
2121
#case 2: our max subarray is wrapping i.e circular
22-
22+
2323
# case 1 is easy to find
24-
# to find case 2 what we can do is if we multiply each nums element by -1 and
24+
# to find case 2 what we can do is if we multiply each nums element by -1 and
2525
# on that find kadanes then we will get sum of elements which is not part of maxsubarray in case2 (not part because we negate)
2626
# now subtract this newmax in case 2 from total nums sum, we get wrapping sum
2727
# max of case1 and case is our ans
28-
28+
2929
total = sum(nums)
30-
30+
3131
nonwrappingsum = self.kadanes(nums)
32-
33-
# edge case when all elements are -ve then return max negative
32+
33+
# edge case when all elements are -ve then return max negative
3434
if nonwrappingsum<0:
3535
return nonwrappingsum
36-
36+
3737
#negate
3838
for i in range(len(nums)):
3939
nums[i]*=-1
40-
41-
40+
4241
wrappingsum = total-(-self.kadanes(nums)) #-ve because originally it was negated
43-
42+
4443
return max(nonwrappingsum,wrappingsum)
45-
46-
47-
48-
49-

0 commit comments

Comments
 (0)