最大子数组

给定一个整数数组,找到一个具有最大和的子数组,返回其最大和。

给出数组[−2,2,−3,4,−1,2,1,−5,3],符合要求的子数组为[4,−1,2,1],其最大和为6

 

最大字数组,和最小字数组的代码几乎一样。

class Solution {
public:
    /*
     * @param nums: A list of integers
     * @return: A integer indicate the sum of max subarray
     */
    int maxSubArray(vector<int> &nums) {
        // write your code here
        int s=nums[0];
        int x=0;
        int i;
        int l=nums.size();
        for(i=0;i<l;i++)
        { x=x+nums[i];
        if(x>=s) {s=x;}
        if(x<0) {x=0;}
        }
        return s;
    }
};

 
 

posted on 2017-10-18 21:26  20153868  阅读(54)  评论(0)    收藏  举报

导航