[leedcode 53] 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.

public class Solution {
    public int maxSubArray(int[] nums) {
        //本题是求最大连续子序列和,声明一个中间值sum,代表之前的和
        int res=Integer.MIN_VALUE;
        int sum=0;
        for(int i=0;i<nums.length;i++){
            sum+=nums[i];
            res=Math.max(sum,res);
            if(sum<0)
               sum=0;
        }
        return res;
    }
}
/*public int maxSubArray(int[] A) {  
        int max = 0;  
        int res = Integer.MIN_VALUE;  
        for(int i=0;i<A.length;i++){  
            max = max>=0 ? (max+A[i]):A[i];  
            res = Math.max(max, res);  
        }  
        return res;  
    } */

 

posted @ 2015-07-12 21:25  ~每天进步一点点~  阅读(154)  评论(0编辑  收藏  举报