Maximum Subarray

来源:互联网 发布:专业淘宝拍摄 编辑:程序博客网 时间:2024/05/01 10:33

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.

思路:对于每个元素,有两种情况,要么前面的和与它相加比它还小,那就从它另起一组继续往后加;如果加上它后比他大,则可以继续累加。同时用一个全局变量保存当前最大值。注意这里不是只要和增大就继续加,因为是要找到最大的子序列的和,所以强调最大。

class Solution {public:    int maxSubArray(int A[], int n) {        if (n == 0) {            return 0;        }                vector<int> sum(n, 0);        sum[0] = A[0];        int result = A[0];                for (int i = 1; i < n; i++) {            sum[i] = max(A[i], sum[i-1] + A[i]);            result = max(result, sum[i]);        }                return result;    }};



0 0
原创粉丝点击