Skip to content

Commit

Permalink
leetCode
Browse files Browse the repository at this point in the history
  • Loading branch information
wizzhangquan committed Nov 1, 2014
1 parent ec5162c commit e9a6c12
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions Maximum_Subarray.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// Source : https://oj.leetcode.com/problems/maximum-subarray/
// Author : [email protected]
// Date : 2014-11-01

/**********************************************************************************
*
* Find the contiguous subarray within an array (containing at least one number)
* which has the largest sum.
*
* For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
* the contiguous subarray [4,−1,2,1] has the largest sum = 6.
*
* More practice:
*
* If you have figured out the O(n) solution, try coding another solution using
* the divide and conquer approach, which is more subtle.
*
*
**********************************************************************************/
#include <iostream>

using namespace std;

int maxSubarray(int A[], int n) {
int max, tmp;
tmp=max=A[0];
for(int i=1; i<n; i++) {
if(tmp>=0) tmp+=A[i];
else tmp=A[i];
if(tmp>max)
max=tmp;
}
return max;
}
int main(void) {
int A[] = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
cout<<maxSubarray(A, 9);
return 0;
}

0 comments on commit e9a6c12

Please sign in to comment.