-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDay15.cpp
44 lines (42 loc) · 911 Bytes
/
Day15.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/*
Author: Aryan Yadav
Maximum Sum Circular Subarray
Complexity:O(n)
Algorithm: Kadane's Algorithm
Difficulty: Medium
*/
using namespace std;
class Solution
{
public:
int kadane(vector<int> &a)
{
int msf = 0;
int me = -1e9;
int n = a.size();
for (int i = 0; i < n; i++)
{
msf += a[i];
if (msf > me)
me = msf;
if (msf < 0)
msf = 0;
}
return me;
}
int maxSubarraySumCircular(vector<int> &a)
{
int sum1 = kadane(a);
int wrap = 0;
int n = a.size();
for (int i = 0; i < n; i++)
{
wrap += a[i];
a[i] *= -1;
}
wrap += kadane(a);
if (sum1 < 0 && wrap == 0)
wrap = sum1;
return max(sum1, wrap);
}
};