剑指offer--(1)连续子数组的最大和--Java描述

写在前面:

    使用动态规划求解

    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;
	}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值