天天看點

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.

分析:

尋找一個子串,使得它們的和最大。

思路:

[a1, a2, a3, a4, a5, a6, … an]

順序周遊每個數,周遊到第n個數時,儲存包含該位的最大數。即an = max(an-1 + an, an).最後周遊擷取最大值即可。

這個跟在兩個字元串裡尋找最大子串是一樣的問題。

分析:

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        vector<int> result;
        int len = nums.size();
        int n = nums[];
        result.push_back(nums[]);
        for(int i = ; i< len; i++)
        {
            if(result[i-] > )
            {
                result.push_back(result[i -] + nums[i]);
                if((result[i -] + nums[i]) > n) n = result[i -] + nums[i];
            }
            else
            {
                result.push_back(nums[i]);
                if(nums[i] > n) n = nums[i];
            }
        }
        return n;
    }
};