最大子数组

来源:互联网 发布:linux sleep 1s 编辑:程序博客网 时间:2024/06/10 18:08

最大字数组

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

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;
    }
};