lintcode-easy-Maximum Subarray

Given an array of integers, find a contiguous subarray which has the largest sum.

Given the array [−2,2,−3,4,−1,2,1,−5,3], the contiguous subarray[4,−1,2,1] has the largest sum = 6.

public class Solution {
    /**
     * @param nums: A list of integers
     * @return: A integer indicate the sum of max subarray
     */
    public int maxSubArray(int[] nums) {
        // write your code
        if(nums == null || nums.length == 0)
            return 0;
        
        int result = nums[0];
        int sum = nums[0];
        
        for(int i = 1; i < nums.length; i++){
            if(sum < 0){
                sum = 0;
            }
            sum += nums[i];
            if(result < sum)
                result = sum;
        }
        
        return result;
    }
}

 

posted @ 2016-02-27 08:21  哥布林工程师  阅读(100)  评论(0编辑  收藏  举报