理解,temp[i] 表明前i項的和,temp[i]的值取決於temp[i-1]的值(temp[i-1]是前 i-1項的和),試想,若是temp[i-1]<0的話,繼續加的話反而會將總體值削減了,獲得的狀態轉移方程爲:temp[i] = (temp[i-1]>0?temp[i-1]:0)+a[i];html
只求最大值:spa
// 狀態轉移方程爲 temp[i] = (temp[i-1]>0?temp[i-1]:0)+a[i]; public static int getMaxSubSet(int[] a) { int len = a.length; int tempMax = a[0], max = a[0]; // tempMax 存儲的是狀態方程的temp[i-1]項和 for (int i = 1; i < len; i++) { // 循環從下標1開始,第一次循環至關於求temp[1] = (temp[0]>0?temp:0)+a[1] tempMax = (tempMax > 0 ? tempMax : 0) + a[i]; max = (max > tempMax ? max : tempMax); } return max; }
求最大值及連續子序的起始:.net
public static int getMax(int[] a) { int start = 0,end = 0; int len = a.length; int tempMax = a[0], max = a[0]; // tempMax 存儲的是狀態方程的temp[i-1]項和 for (int i = 1; i < len; i++) { // 循環從下標1開始,第一次循環至關於求temp[1] = (temp[0]>0?temp:0)+a[1] if(tempMax > 0) { tempMax += a[i]; }else { tempMax = a[i]; //從i下標從新計算 start = i; } if(tempMax > max) { max = tempMax; end = i; //記錄終點下標 } } System.out.println("連續下標從"+start+"到"+end); return max; }