LeetCode:Maximum Subarray

来源:互联网 发布:淘宝店铺文案范文 编辑:程序博客网 时间:2024/06/06 03:15

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.

直接想法遍历数组,累加过程中记录累加的出来的最大值,只要前若干项和小于0,则清空其值重新累加。

public class Solution {    public int maxSubArray(int[] A) {        int maxn=Integer.MIN_VALUE,res=0,len=A.length;                for(int i=0;i<len;i++)        {            res+=A[i];            maxn=Math.max(maxn,res);            if(res<0)res=0;        }     return maxn;    }}
其实还可以利用动态规划的思想,记录前n-1项累加和和当前项之和,并与当前项比较大小,记录大值(实质还是前若干项和小于0时抛弃重新计算):

public class Solution {    public int maxSubArray(int[] A) {        int curSum=A[0],maxn=A[0],len=A.length;            for(int i=1;i<len;i++)        {            curSum=Math.max(A[i],curSum+A[i]);            maxn=Math.max(curSum,maxn);        }        return maxn;    }}


0 0
原创粉丝点击