写在前面:
使用动态规划求解
F(i)=以array[I]为末尾元素的子数组的和的最大值。 公式:F(i)=max( F(i-1) + array[i] , array[i] )
设res=所有子数组的和的最大值。res=max( res , F(i))
例如:
数组为:【6,-3,-2,7,-15,1,2,2】
初始状态:
i=0时
F(0)=6
res=6
i=1时
F(1)=max( F(0)-3 , -3)=max( 6-3 ,-3)=3
res=max( 6 , 3)=6
i=2时
F(2)=max( F(1)-2 ,-2)=max( 1 ,-2 )=1
res=max( res ,F(2) )=max( 6 , 1 )=6
i=3时
F(3)=max(F(2)+7 ,7)=max( 8 , 7 )=8
res=max(res , F(3) )=max( 6 , 8 )=8
i=4时
F(4)=max( F(3)-15 ,-15)=max( -7 , -15 )=-7
res=max( res , F(4) )=max ( 8 , -7 )=8
以此类推
程序代码实现:
package test6;
public class Test {
public static void main(String[] args) {
int array1[] = new int[] { 6,-3,-2,7,-15,1,2,2};
maxTotal(array1);
}
public static int maxTotal(int[] array) {
int max = array[0];
int res = array[0];
for (int i = 1; i < array.length; i++) {
max = Math.max(max + array[i], array[i]);
System.out.println("max:"+max);
res = Math.max(max, res);
System.out.println("res:"+res);
}
return res;
}
}