Skip to content

Commit 1307af5

Browse files
authored
Max Sum Contiguous Subarray
Find the contiguous subarray within an array, A of length N which has the largest sum.
1 parent eb59004 commit 1307af5

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

Dynamic-Programming/maxSubArray.cpp

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
int Solution::maxSubArray(const vector<int> &A) {
2+
int n = A.size();
3+
if(n==0) return 0;
4+
if(n == 1) return A[0];
5+
int S[n+1]={0};
6+
S[0] = A[0];
7+
int i, maxSum = A[0];
8+
for(i = 1; i < n; ++i) {
9+
S[i] = max(S[i-1]+A[i], A[i]);
10+
maxSum = max(S[i], maxSum);
11+
}
12+
return maxSum;
13+
}
14+
15+
int max(int a, int b) {
16+
return a > b? a:b;
17+
}

0 commit comments

Comments
 (0)