Maximum Subarray

来源:互联网 发布:希捷 数据恢复服务 编辑:程序博客网 时间:2024/05/16 12:23

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.

click to show more practice.

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.


题目解析:

(1)保证左边的sum是最大的。

(2)考虑边界条件n == 1


#include <iostream>using namespace std;int maxSubArray(int A[], int n) {int maxSum = INT_MIN;int sum = 0;if(n == 1){return A[n-1];}int i = 0;while(i < n){if(A[i] > sum + A[i])sum = A[i];elsesum = sum + A[i];if(maxSum < sum)maxSum = sum;i++;}return maxSum;}int main(void){int A[] = {-2,1,-3,4,-1,2,1,-5,4};cout << maxSubArray(A, 9) << endl; system("pause");return 0;}


0 0