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.

 

class Solution {
    public int maxSubArray(int[] nums) {
         if(nums==null||nums.length==0) return 0;
            
            int maxSum=nums[0];//最大和。初始值要为第一项
            int theSum=nums[0];//当前项为止的最大和。初始值要为第一项,不要为0
        //如果当前项的最大和小于等于0,那么theSum应该要从该项后面开始重新计算和,因为负数对和没有正帮助。
for(int i=1;i<nums.length;i++){ if(theSum>0) theSum=theSum+nums[i]; else theSum=nums[i];//初始值不为零,则这里初始化时也就不是0, if(maxSum<theSum) maxSum=theSum; } return maxSum; } }

初始为0,若只有一个元素,且为负数,此时就会输出0.不对

posted on 2017-12-19 15:25  夜的第八章  阅读(173)  评论(0编辑  收藏  举报

导航