杭电oj-1003(Max Sum)

Problem Description

Given a sequence a[1],a[2],a[3]......a[n], your job is to
calculate the max sum of a sub-sequence. For example, given 
(6,-1,5,4,-7), the max sum in this sequence is 6 + (-1) + 5 + 4 = 
14.

Input

The first line of the input contains an integer T(1<=T<=20) which 
means the number of test cases. Then T lines follow, each line 
starts with a number N(1<=N<=100000), then N integers 
followed(all the integers are between -1000 and 1000).

Output

For each test case, you should output two lines. The first line 
is "Case #:", # means the number of the test case. The second 
line contains three integers, the Max Sum in the sequence, the 
start position of the sub-sequence, the end position of the sub-
sequence. If there are more than one result, output the first 
one. Output a blank line between two cases.

Sample Input

2
5 6 -1 5 4 -7
7 0 6 -1 1 -6 7 -5

Sample Output

Case 1:
14 1 4

Case 2:
7 1 6

Author

Ignatius.L

本题求解的是最大子段问题,也就是说从任何一个数开始,连续的中间不能间断,几个数都可以,把这些数加在一起求出最大值,然后返回这个最大值,并且返回初始下标和终止的下标。

这道题原本是笔者数据结构课上的一道题,我当初做出来的时候,那个高兴啊,没想到在acm里原来是道水题,O(∩_∩)O哈哈哈~,这道题采用暴力求解,分治算法都是可以解决的,当然最好的思想还是动态规划的做法,时间负责度仅为O(n),在一次循环中动态更新最大值和起始下标与终止下标就可以实现啦。

代码:


import java.util.Scanner;

public class Main1003 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int T, N, num, startP = 1, endP = 1;
        T = in.nextInt();
        int m = T;
        while (T-- > 0) {
            int max = -1001, temp = 1, sum = 0;
            N = in.nextInt();
            for (int i = 1; i <= N; i++) {
                num = in.nextInt();
                sum += num;
                if (sum > max) {
                    max = sum;
                    startP = temp;
                    endP = i;
                }
                if (sum < 0) {
                    sum = 0;
                    temp = i + 1;
                }
            }
            System.out.println("Case " + (m - T) + ":");
            System.out.println(max + " " + startP + " " + endP);
            if (T != 0) {
                System.out.println("");
            }
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,845评论 18 139
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,767评论 0 33
  • 树形动态规划,顾名思义就是树+DP,先分别回顾一下基本内容吧:动态规划:问题可以分解成若干相互联系的阶段,在每一个...
    Mr_chong阅读 1,502评论 0 2
  • 本系列文章面向深度学习研发者,希望通过Image Caption Generation,一个有意思的具体任务,深入...
    imGeek阅读 1,828评论 0 8
  • 文|阿狸阿离 你就是你读过的书。——阿狸阿离 1. 我堂姐今年才二十几岁,过年的时候不敢回家。因为每个人都在问, ...
    明月心2017阅读 455评论 1 4