Max-Sum Subarray

来源:互联网 发布:淘宝400电话 编辑:程序博客网 时间:2024/05/17 23:10

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.

11/1

scan the array and push each element to a stack, if the top is negative, simply push, otherwise, pop-add and then push;

in fact just need to keep the top, so simplify the algorithm

public class Solution {    public int maxSubArray(int[] A) {        int len = A.length;        if(len == 0)    return 0;                int max_sum = A[0];        int top = A[0];                for(int i=1; i<len; i++){            int a = A[i];            if(top < 0){                top = a;            }else{                top += a;            }                        max_sum = Math.max(max_sum, top);            max_sum = Math.max(max_sum, a);        }                return max_sum;            }}


0 0
原创粉丝点击