【LeetCode-面試演算法經典-Java實現】【053-Maximum Subarray(最大子數組和)】,-javasubarray
【053-Maximum Subarray(最大子數組和)】【LeetCode-面試演算法經典-Java實現】【所有題目目錄索引】原題
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.
題目大意
求數組的最大子數組的和。
解題思路
動態規劃問題,已知了前k個元素的最大子序列和為maxSub(已經被記錄下來了),以及一個臨時和sum,如果添加了第k+1這個元素,由於是連續子序列這個限制,所以如果k+1這個元素之前的和是小於0的,那麼對於增大k+1這個元素從而去組成最大子序列是沒有貢獻的,所以可以把sum 置0。
代碼實現
演算法實作類別
public class Solution { public int maxSubArray(int[] nums) { // 參數校正 if (nums == null || nums.length < 1) { throw new IllegalArgumentException(); } int max = Integer.MIN_VALUE; int curSum = 0; for (int i : nums) { // 當前和小於0,就將當前值賦給curSum if (curSum <= 0){ curSum = i; } // 否則進行累加 else { curSum += i; } // 儲存較大的值 if (max < curSum) { max = curSum; } } return max; }}
評測結果
點擊圖片,滑鼠不釋放,拖動一段位置,釋放後在新的視窗中查看完整圖片。
特別說明
歡迎轉載,轉載請註明出處【http://blog.csdn.net/derrantcm/article/details/47120487】
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。