Max Sum(最大连续子序列和)
题目链接: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).
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
题目大意
给定序列,计算最大的连续子序列和以及对应的开始下标和结束下标。例如,给定 (6,-1,5,4,-7),此序列中的最大和为 6 + (-1) + 5 + 4 = 14,开始下标为1,结束下标为4。
解题思路
本人比较菜所以首先考虑暴力法,保存数组的第一位为max,计算每一个子序列的和与max进行比较,但时间复杂度会达到O(n^3),超时。因此进行优化:
-
(1)如果当前子序列的和>=0
- (1.1) 如果当前子序列的和>max,则更新max的值,保存当前的开始下标和结束下标
- (1.2) 如果当前子序列的和<=max,则继续遍历 (2)如果当前子序列的和<0
- (2.1)如果保存的max<0,则继续循环比较
- (2.2)如果保存的max>=0,则跳过当前循环
代码
#include <iostream>
using namespace::std;
int main(int argc, const char * argv[]) {
int t, count = 1;
cin >> t;
while (t--) {
//初始化
int n, i = 0, j = 0;
int a[100000];
memset(a, 0, sizeof(a));
//读取数据
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a[i];
}
//初始最大值为a[0], 起点为1, 终点为1
int max = a[0], start = 1, end = 1;
for (i = 0; i < n; i++) {
int temp = a[i];
//解决输入的值都为负数
if (temp > max) {
max = temp;
start = i + 1;
end = i + 1;
}
//遍历
for (j = i+1; j < n; j++) {
temp += a[j];
//当前结果小于0且最大值不小于0则退出当前循环
if (temp < 0 && max >= 0) {
break;
}
//当前结果大于max则更新max
if (temp > max) {
max = temp;
start = i + 1;
end = j + 1;
}
}
}
//输出结果
cout << "Case " << count << ":" << endl;
cout << max << " " << start << " " << end << endl;
if (t) {
cout << endl;
}
count++;
}
return 0;
}
个人学习经验,欢迎各位指导