Maximum Subarray

来源:互联网 发布:php socket可以做什么 编辑:程序博客网 时间:2024/06/05 09:27

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.
时间复杂度为O{n}的解法是维护一个局部最优解和全局最优解。全局最优解的初始值要定义为Integer.MIN_value,之前定义为0,忽略了负数的情况。

public int maxSubArray(int[] nums) {    int sum=Integer.MIN_VALUE;     int current=0;    for(int num:nums){        current=Math.max(current+num, num);        sum=Math.max(current, sum);    }    return sum;    }
原创粉丝点击