Description
石柱上有一排石头键盘,每个键上有一个整数。请你在键盘上选择两个键,使这两个键及其之间的键上的数字和最大。如果这个最大的和不为正,则输出“Game Over”。
Input Format
第1行:键的个数n。
第2..n+1行:键上的数字整数 ai。
−100≤ai≤10
对于70%的数据,2≤n≤1,000
对于100%的数据,2≤n≤1,000,000
Output Format
一行,最大和或者”Game Over”。
Sample Input
5
3
-5
7
-2
8
Sample Output
13
Sample Input
3
-6
-9
-10
Sample Output
Game Over
这是Leetcode上一道题的变形,那道题目是不同是连续数的个数至少为1,直接扫一遍就可以了。这道题目略麻烦一些,需要增加判断连续子列长度是否至少为2。
思路是基于“前面扫过小于零就重置”的思想,再对特例进行处理。
#include<iostream>
using namespace std;
int main(){
int n;
cin>>n;
int sum{};
int ans = -1;
bool f = false;
int last;
bool lastf = false;
while(n--){
int t;
cin>>t;
sum+=t;
if (f) ans = sum>ans?sum:ans; //如果大于等于两个进行比较
if (lastf) {
int pair = last+t;
ans = pair>ans?pair:ans;
} //由于可能出现 负数 + 正数为极大值的情况,所以对每一个pair进行求和,lastf是为了避免第一个数的情况
if(sum<0){
sum = 0;
f = false;
}
else f = true; //如果大于等于零就留下,继续后扫
last = t;
lastf = true;
}
cout<<(ans<=0?"Game Over":to_string(ans));
}