File tree 1 file changed +17
-23
lines changed
scripts/algorithms/M/Maximum Sum Circular Subarray
1 file changed +17
-23
lines changed Original file line number Diff line number Diff line change
1
+ # Runtime: 729 ms (Top 66.43%) | Memory: 18.9 MB (Top 76.46%)
1
2
class Solution :
2
-
3
+
3
4
def kadanes (self ,nums ):
4
-
5
+
5
6
#kadanes algo
6
-
7
+
7
8
max_till_now = nums [0 ]
8
9
curr_max = nums [0 ]
9
-
10
+
10
11
for i in range (1 ,len (nums )):
11
12
curr_max = max (curr_max + nums [i ],nums [i ])
12
13
max_till_now = max (max_till_now ,curr_max )
13
-
14
+
14
15
return max_till_now
15
-
16
-
16
+
17
17
def maxSubarraySumCircular (self , nums : List [int ]) -> int :
18
-
18
+
19
19
#there will be 2 case
20
20
#case 1 : our max subarray is not wrapping i.e not circular
21
21
#case 2: our max subarray is wrapping i.e circular
22
-
22
+
23
23
# 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
25
25
# on that find kadanes then we will get sum of elements which is not part of maxsubarray in case2 (not part because we negate)
26
26
# now subtract this newmax in case 2 from total nums sum, we get wrapping sum
27
27
# max of case1 and case is our ans
28
-
28
+
29
29
total = sum (nums )
30
-
30
+
31
31
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
34
34
if nonwrappingsum < 0 :
35
35
return nonwrappingsum
36
-
36
+
37
37
#negate
38
38
for i in range (len (nums )):
39
39
nums [i ]*= - 1
40
-
41
-
40
+
42
41
wrappingsum = total - (- self .kadanes (nums )) #-ve because originally it was negated
43
-
42
+
44
43
return max (nonwrappingsum ,wrappingsum )
45
-
46
-
47
-
48
-
49
-
You can’t perform that action at this time.
0 commit comments