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.

click to show more practice.

More practice:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

標籤: Divide and Conquer Array Dynamic Programming

分析:最大連續子和問題,我們可以從頭遍歷陣列,遍歷到元素 i 時有兩個選擇:

1.如果它大於等於零時,那就將它與前面的子和sum相加。

2.如果它小於零時,則由該元素作為下一個子和sum的開頭元素

在遍歷陣列的同時記錄最大的子和sumj即為最大連續子和;

這裡用動態規劃的方法解決,設dp[i]表示從首元素到元素i的最大連續子和,所以有狀態轉移方程為:

dp[i]=max(dp[i-1]+array[i],array[i]);

參考程式碼:

 public class Solution {
public int maxSubArray(int[] A) {
int len=A.length;
int ret=Integer.MIN_VALUE;
int dp=0;
for(int i=0;i<len;i++){
dp=Math.max(dp+A[i], A[i]);
ret=Math.max(ret, dp);
}
return ret;
}
}