HDU 1003 Max Sum(简单动态规划)

题目链接:http://acm.hdu.edu.cn/game/entry/problem/show.php?chapterid=3&sectionid=2&problemid=1

题意解析:找到给出数组中的一个子数组,它的和最大

解题思路:比如要找  1 -6 7 -5中最大子串,这个子串肯定是以正数为首,并且以正数结尾,假定子串为第一个数字,现在要拓展它,如果它加上下一个数字大于下一个数字,那就是有利的,可以加;如果加上下一个数字不如下一个数字大,那么这是不划算的,1 -6 再加上7,不如直接从7开始

核心:看纳入下一个数字是否划算,如果不划算,不如直接从下一个数字开始

代码:

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int t = in.nextInt();
        for (int i = 1; i <= t; i++) {
            int n = in.nextInt();
            int[] list = new int[n];
            for (int j = 0; j < n; j++) {
                list[j] = in.nextInt();
            }
            
            int end = 0, start = 0, eend = 0, sstart = 0;
            int he = list[0];
            int max = list[0];
            for (int j = 1; j < list.length; j++) {
                if (he+list[j] < list[j]) {//等价于he<0
                    start = j;
                    end = j;
                    he = list[j];
                } else {
                    he += list[j];
                    end++;
                }
                if (max < he) {
                    max = he;
                    eend = end;
                    sstart = start;
                }
            
        }
            System.out.println("Case "+i+":");
            System.out.println(max+" "+(sstart+1)+" "+(eend+1));
            if(i!=t) {
                System.out.println();
            } 
        
       }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值