LeetCode:Maximum Subarray

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;
    }
}


發佈了34 篇原創文章 · 獲贊 0 · 訪問量 9648
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章