Maximum Subarray

来源:互联网 发布:python tf idf 的代码 编辑:程序博客网 时间:2024/06/06 15:52

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.


代码:

class Solution {
public:
    int maxSubArray(int[] nums) {
        

         int max = Integer.MIN_VALUE;//首先设出最小值        int sum = 0;//每一个分组的和        int i = 0;        while(i < nums.length){            sum += nums[i];//每一个分组的前n项和            if(max < sum){                max = sum;//取最大和            }            if(sum < 0){//假设<0。分组结束,开始下一组                sum = 0;            }            i++;        }        return max;


    }
};

原创粉丝点击