LeetCode--Maximum Subarray

Maximum Subarray

Question

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.
m

解题思想

分治的思想,将数组分解为更小的两个子数组,最大序列要么再两边,要么再中间,只有这三种情况。

具体实现

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;


class Solution {
public:
    // 利用分治的思想
    int maxSubArray(vector<int>& nums) {
        return maxSum3(nums, 0, nums.size() - 1);
    }
    int maxSum3(vector<int>& nums, int p, int q) {
        if (p > q) {
            return 0;
        }
        if (p == q) {
            return nums[p];
        }
        int lmax = 0;
        int lsum = 0;
        int m = (p + q) / 2;
        for (int i = m; i >= p; i--) {
            lsum += nums[i];
            lmax = max(lmax, lsum);
        }
        int rmax = 0;
        int rsum =0;
        for (int j = m + 1; j <= q; j++) {
            rsum += nums[j];
            rmax = max(rsum, rmax);
        }
        int total = lmax + rmax;
        if (total == 0)
            total = INT_MIN;
        return max(max(total, maxSum3(nums, p, m)), maxSum3(nums, m + 1, q));

    }
};
posted @ 2017-03-12 21:50  清水汪汪  阅读(190)  评论(0编辑  收藏  举报