leetcode -- Maximum Subarray

Maximum Subarraycode

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.ip

For example, given the arrayleetcode

[-2,1,-3,4,-1,2,1,-5,4],

the contiguous subarrayget

[4,-1,2,1]

has the largestit

sum = 6.

Solutionio

class Solution {
    public int maxSubArray(int[] nums) {
        int max = Integer.MIN_VALUE, sum = 0;
        for(int i=0; i<nums.length; i++){
            if(sum <0)
                sum = nums[i];
            else
                sum += nums[i];
            if (sum>max)
                max = sum;
        }
        return max;
    }
}
相關文章
相關標籤/搜索