Skip to content

Commit 82fbf91

Browse files
Create Day 15 Maximum Sum Circular Subarray.cpp
1 parent e1831d0 commit 82fbf91

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed
+86
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
PROBLEM:
2+
3+
4+
Given a circular array C of integers represented by A, find the maximum possible sum of a non-empty subarray of C.
5+
Here, a circular array means the end of the array connects to the beginning of the array. (Formally, C[i] = A[i] when
6+
0 <= i < A.length, and C[i+A.length] = C[i] when i >= 0.)
7+
Also, a subarray may only include each element of the fixed buffer A at most once. (Formally, for a subarray C[i],
8+
C[i+1], ..., C[j], there does not exist i <= k1, k2 <= j with k1 % A.length = k2 % A.length.)
9+
10+
11+
Example 1:
12+
Input: [1,-2,3,-2]
13+
Output: 3
14+
Explanation: Subarray [3] has maximum sum 3
15+
16+
Example 2:
17+
Input: [5,-3,5]
18+
Output: 10
19+
Explanation: Subarray [5,5] has maximum sum 5 + 5 = 10
20+
21+
Example 3:
22+
Input: [3,-1,2,-1]
23+
Output: 4
24+
Explanation: Subarray [2,-1,3] has maximum sum 2 + (-1) + 3 = 4
25+
26+
Example 4:
27+
Input: [3,-2,2,-3]
28+
Output: 3
29+
Explanation: Subarray [3] and [3,-2,2] both have maximum sum 3
30+
31+
Example 5:
32+
Input: [-2,-3,-1]
33+
Output: -1
34+
Explanation: Subarray [-1] has maximum sum -1
35+
36+
Note:
37+
38+
1. -30000 <= A[i] <= 30000
39+
2. 1 <= A.length <= 30000
40+
41+
42+
43+
SOLUTION:
44+
45+
46+
class Solution {
47+
private:
48+
49+
int kadane(vector<int>& A)
50+
{
51+
int ans=INT_MIN,s=0;
52+
53+
for(auto k:A)
54+
{
55+
s=max(s+k,k);
56+
ans=max(ans,s);
57+
}
58+
59+
return ans;
60+
}
61+
62+
public:
63+
int maxSubarraySumCircular(vector<int>& A) {
64+
65+
int s1,s2,i,n,s=0,ans;
66+
s1=kadane(A); // if max subarray is in middle
67+
68+
n=A.size();
69+
70+
for(i=0;i<n;i++)
71+
{
72+
s+=A[i];
73+
A[i]=-A[i];
74+
}
75+
76+
s2=kadane(A); //max subarray sum with negative elements
77+
78+
if(s+s2==0)
79+
ans=s1;
80+
else
81+
ans=max(s1,s+s2);
82+
83+
return ans;
84+
85+
}
86+
};

0 commit comments

Comments
 (0)