File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ Author: Aryan Yadav
3
+ Maximum Sum Circular Subarray
4
+
5
+ Complexity:O(n)
6
+ Algorithm: Kadane's Algorithm
7
+ Difficulty: Medium
8
+ */
9
+
10
+ using namespace std ;
11
+ class Solution
12
+ {
13
+ public:
14
+ int kadane (vector<int > &a)
15
+ {
16
+ int msf = 0 ;
17
+ int me = -1e9 ;
18
+ int n = a.size ();
19
+ for (int i = 0 ; i < n; i++)
20
+ {
21
+ msf += a[i];
22
+ if (msf > me)
23
+ me = msf;
24
+ if (msf < 0 )
25
+ msf = 0 ;
26
+ }
27
+ return me;
28
+ }
29
+ int maxSubarraySumCircular (vector<int > &a)
30
+ {
31
+ int sum1 = kadane (a);
32
+ int wrap = 0 ;
33
+ int n = a.size ();
34
+ for (int i = 0 ; i < n; i++)
35
+ {
36
+ wrap += a[i];
37
+ a[i] *= -1 ;
38
+ }
39
+ wrap += kadane (a);
40
+ if (sum1 < 0 && wrap == 0 )
41
+ wrap = sum1;
42
+ return max (sum1, wrap);
43
+ }
44
+ };
You can’t perform that action at this time.
0 commit comments