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。spa
算法實現類.net
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; } }