博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
1007. Maximum Subsequence Sum (25)
阅读量:5290 次
发布时间:2019-06-14

本文共 2214 字,大约阅读时间需要 7 分钟。

Given a sequence of K integers { N1, N2, ..., NK }. A continuous subsequence is defined to be { Ni, Ni+1, ..., Nj } where 1 <= i <= j <= K. The Maximum Subsequence is the continuous subsequence which has the largest sum of its elements. For example, given sequence { -2, 11, -4, 13, -5, -2 }, its maximum subsequence is { 11, -4, 13 } with the largest sum being 20.

Now you are supposed to find the largest sum, together with the first and the last numbers of the maximum subsequence.

Input Specification:

Each input file contains one test case. Each case occupies two lines. The first line contains a positive integer K (<= 10000). The second line contains K numbers, separated by a space.

Output Specification:

For each test case, output in one line the largest sum, together with the first and the last numbers of the maximum subsequence. The numbers must be separated by one space, but there must be no extra space at the end of a line. In case that the maximum subsequence is not unique, output the one with the smallest indices i and j (as shown by the sample case). If all the K numbers are negative, then its maximum sum is defined to be 0, and you are supposed to output the first and the last numbers of the whole sequence.

Sample Input:

10-10 1 2 3 4 -5 -23 3 7 -21

Sample Output:

10 1 4

 

/* 求最大子序列  并记录该子序列的第一个数 和最后一个数。 */ #include "iostream"using namespace std;int main() {    int n;    int thisSum = 0;    int a[10000];    int MAX = -1;    int start, end, endi, starti;    int cnt = 0;    cin >> n;    bool flag = true;    for (int i = 0; i < n; i++) {        cin >> a[i];        if (a[i] >= 0)            flag = false;    }    if (flag) {        cout << "0 " << a[0] <<" "<< a[n - 1] << endl;    }    else {        for (int i = 0; i < n; i++) {            thisSum += a[i];            if (thisSum > MAX) {                MAX = thisSum;                starti = i - cnt;                end = a[i];            }            if (thisSum < 0) {                thisSum = 0;                cnt = 0;            }            else {                cnt++;            }        }        cout << MAX << " " << a[starti] << " " << end << endl;    }    return 0;}

 

转载于:https://www.cnblogs.com/minesweeper/p/6282357.html

你可能感兴趣的文章
<php>Ajax基本格式
查看>>
mybatis中的多条件查询
查看>>
C# WebBrowser 抓图获取网页验证码
查看>>
Linux 终端输入保存到一个文件中
查看>>
未加载opencv_world330.pdb
查看>>
Java排序算法(三):直接插入排序
查看>>
iOS 开发百问(5)
查看>>
删除单链表中某一个值
查看>>
第五周学习进度
查看>>
事务的应用
查看>>
Excel Vlookup多条件查询 , 列转行
查看>>
浅谈JS继承
查看>>
2018-2019-2 20175224 实验一《Java开发环境的熟悉》实验报告
查看>>
元素的offsetParent offsetLeft offsetTop属性
查看>>
NOI2015
查看>>
生成器表达式
查看>>
第三天运算符--三元操作符
查看>>
C#学习笔记-输入数据判断(int、double、string)
查看>>
uva 10881
查看>>
ubuntu node.js Binaries方式安装(二进制文件安装)
查看>>