PAT (Advanced Level)1007解

因为最近在刷题库,想想就把本人可以想到的解法写到博客里,作为整理归纳。未必是最优解,还请各位高手多多包涵,能够指点指点。

题目要求
1007 Maximum Subsequence Sum (25 分)
Given a sequence of K integers { N​1​​ , N​2​​ , …, N​K​​ }. A continuous subsequence is defined to be { N​i​​ , N​i+1​​ , …, N​j } 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

解题思路
本文的解题思路采用的是《算法笔记》中介绍的动态规划问题的延伸扩展。
数组长度达到10的5次方级别,暴力解法时间复杂度为O(n2),会超时。注意到每次检测的时候其实只和数列到前面一个数的最大和有关,没有必要每一次都要从最左边一项开始,从而可以将复杂度降低到O(n)。
我针对题目进行修改的部分为,由于题目要求输出首尾数字,将dp数组改为二维,在每次记录最大和的同时,记录着一列的开头(结尾强制为当前位置k,就没有必要另外记录了)。又可以注意到,如果最大和序列有算上当前项,那么当前序列的头和上一个数字的序列头相同,即 dp[i][1]=dp[i-1][1]。最后知道头尾就可以很容易输出了。(其实很明显,我这么做是增加了代码的复杂情况,由于我一开始看错了题目,就简单的修改了一下。大佬勿喷)
注意事项
1.边界情况,即全负数的情况的输出情况需特殊处理
2.也就是我看错的题目。我不小心把序列第一个数字和最后一个数字看成了序列的头和序列的尾的位置。注意审题!!!!!!
代码部分

 #include<cstdio>
 #include<algorithm>
 using namespace std;
 const int maxn=10010;
 int A[maxn],dp[maxn][2];
 int main(){
   int n ;
   scanf("%d",&n);
   for(int i =0;i<n;i++){
   	scanf("%d",&A[i]);
	}
	dp[0][0]=A[0];
	dp[0][1]=0;
   for(int i =1;i<n;i++){
     dp[i][0]=max(A[i],dp[i-1][0]+A[i]);  
     if(A[i]>dp[i-1][0]+A[i])
     dp[i][1]=i;
     else
     dp[i][1]=dp[i-1][1];
    } 
   int k =0;
   for(int i =1;i<n;i++){
     if(dp[i][0]>dp[k][0]){
       k=i;
     }
   }
   if(dp[k][0]<0){
   printf("0 %d %d",A[0],A[n-1]);   	
   }
   else
   printf("%d %d %d",dp[k][0],A[dp[k][1]],A[k]);
   return 0;
 }

运行结果
在这里插入图片描述

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值