[LeetCode] Maximum Subarray
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.
经典DP。二分版,过几日放上。
1 class Solution { 2 public: 3 int maxSubArray(int A[], int n) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 int ret = INT_MIN; 7 int sum = 0; 8 for(int i = 0; i < n; i++) 9 { 10 sum = max(sum + A[i], A[i]); 11 ret = max(sum, ret); 12 } 13 14 return ret; 15 } 16 };