Max Sum
Posted vetsama
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Max Sum相关的知识,希望对你有一定的参考价值。
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).
OutputFor 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 -5Sample Output
Case 1: 14 1 4 Case 2: 7 1 6
最大子序列,判断当前这一个数加上前一个数为结尾的最大子序列和以当前的数开头的两个值的大小。
也可以转化为,前一个数为结尾的子序列不小于0,就把当前数加入序列
记录起点,当找到一个大值的时候保存起点和重点
注意格式(笑)
max起始值选择-1001
#include<cstdlib> #include<iostream> using namespace std; int main() { int n = 0; cin >> n; for (int j = 1; j <= n; j++) { int m = 0; cin >> m; int a[100001] = { 0 }; for (int i = 1; i <= m; i++) { cin >> a[i]; } int temp = 0; int t = 1; int max = -1001; int end = 1; int begin = 1; for (int i = 1; i <= m; i++) { if (temp < 0) { temp = a[i]; t = i; } else { temp += a[i]; } if (temp > max) { max = temp; begin = t; end = i; } } printf("Case %d: %d %d %d ", j, max, begin, end); if (j != n) { cout << endl; } } return 0; }
以上是关于Max Sum的主要内容,如果未能解决你的问题,请参考以下文章
HDU1244:Max Sum Plus Plus Plus
leetcode_1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold_[二维前缀和](代码片段