当前位置: 首页 > news >正文

1007 Maximum Subsequence Sum——PAT甲级(dp)

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

 solution:
 

#include<bits/stdc++.h>
using namespace std;
bool allnega(vector<int>a)
{for(int i=1;i<a.size();i++){if(a[i]>=0)return false;}return true;
}
int main()
{int k;cin>>k;vector<int>a(k+1);for(int i=1;i<=k;i++)cin>>a[i];int maxans=0;vector<int>pre(k+1,0);pre[0]=-1;int tmp;int ansl=0,ansr=0;if(allnega(a)){cout<<0<<' '<<a[1]<<' '<<a[k]<<endl;return 0;}else{for(int i=1;i<=k;i++){pre[i]=max(pre[i-1]+a[i],a[i]);if(pre[i-1]<0){tmp=a[i];}if(pre[i]>maxans){ansr=a[i];ansl=tmp;}maxans=max(maxans,pre[i]);}cout<<maxans<<' '<<ansl<<' '<<ansr<<endl;}
}

          测试点3:只有一个数字。

求最大子序列和以及左右边界数字。

题目自带条件:所有数字均为负数时特判。这个条件如果不存在,上述在仅有一个负数时会产生错误,虽然不影响这道题但是待解决。即maxans初始化为0导致的需要初始化为a[0],这样能保证稳定求出最大值。但是如果初始化为a[0]上述无法解决左右边界问题,看了其他题解不少也存在这个问题。插眼


http://www.mrgr.cn/news/45431.html

相关文章:

  • 简历修订与求职经历 - Chap02.
  • 使用AutoDL安装Mamba官方代码
  • 怎么在抖音直播间录屏?主播会知道吗?录屏软件推荐
  • 【大模型报告】中国信通院2024大模型典型示范应用案例集+上交 动手学大模型教程来袭!
  • C++(运算符重载)
  • 【读书笔记·VLSI电路设计方法解密】问题3:在最新工艺下,数百万-千万门级电路设计的挑战
  • CSS 图标和文本对齐
  • 28 Vue3之搭建公司级项目规范
  • 数字王国里的虚拟人——技术、商业与法律解读
  • C++多态常见问题
  • `cd` 后面没有指定任何目录,表示回到用户的主目录(`$HOME`)
  • JavaEE学习一条龙服务————概述
  • 零基础学习 Python 爬虫技术的大纲
  • 2024 Spring 面试题大全:你的成功之路指南
  • 「完美收官」科东软件2024上海国际工博会精彩回顾:鸿道操作系统赋能新型工业化
  • 【华为HCIP实战课程八】OSPF网络类型及报文类型详解,网络工程师
  • List子接口
  • 时序约束进阶四:set_input_delay和set_output_delay详解
  • Xinstall带你解锁App下载归因新姿势,轻松搞定推广难题
  • C++——优先级队列