1007 Maximum Subsequence Sum
题目:1007 Maximum Subsequence Sum
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 Knumbers 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:
1 2 | 10 -10 1 2 3 4 -5 -23 3 7 -21 |
Sample Output:
1 | 10 1 4 |
思路:
1、动态规划状态
dp[i].value 存放以a[i]结尾的连续序列的最大和
dp[i].start存放以a[i]结尾的最大连续序列的第一个数的下标
2、低级错误:输出字符串得要用“”双引号
cout<<'0 ' -> cout<<"0 "
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | #include<stdio.h> #include<iostream> using namespace std; struct DP{ int start, value; }dp[10005]; // dp[i].value 表示以下标为i的数组元素为结尾的子串的最大和 int main(){ int k,index=0; int a[10005]; cin>>k; for ( int i=0; i<k; i++){ cin>>a[i]; } dp[0].start = 0; dp[0].value = a[0]; for ( int i=1; i<k; i++){ if (dp[i-1].value + a[i] > a[i]){ dp[i].value = dp[i-1].value + a[i]; dp[i].start = dp[i-1].start; } else { dp[i].value = a[i]; dp[i].start = i; } } for ( int i=1; i<k; i++){ if (dp[i].value > dp[index].value){ index = i; } } if (dp[index].value < 0){ cout<< "0 " <<a[0]<< ' ' <<a[k-1]; } else { cout<<dp[index].value<< ' ' <<a[dp[index].start]<< ' ' <<a[index]; } return 0; } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!