1006. 求和游戏

Description

石柱上有一排石头键盘,每个键上有一个整数。请你在键盘上选择两个键,使这两个键及其之间的键上的数字和最大。如果这个最大的和不为正,则输出“Game Over"。

Input Format

第1行:键的个数n。

第2..n+1行:键上的数字整数 a i  ai 。

−100≤a i ≤100 −100≤ai≤100

对于70%的数据,2≤n≤1,000 2≤n≤1,000

对于100%的数据,2≤n≤1,000,000 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

代码:

#include <iostream>
#include <cstdio>
using namespace std;
int main(int argc, char const *argv[]) {
    //n 代表元素数量
    int n;
    scanf("%d",&n);
    int a[n];
    for(int i = 0;i < n;i++){
        scanf("%d",&a[i]);
    }
    //max 用来临时记录两个元素之间最大的和,先将前两个元素计入 max
    //imax 用来记录判断过程中 哪一段的和更大
    int max = a[0] + a[1];
    int imax = max;
    for(int i = 2;i < n;i++){
        //如果 a[i - 1] > max 则说明max的元素段中的i - 1之前的元素和为负应舍去
        max < a[i - 1]?max = a[i - 1] + a[i]:max += a[i];
        imax = imax > max?imax:max;//若临时元素段max超过了imax则记录此时出现的最大元素段
    }
    imax > 0?printf("%d%c",imax," \n"[1 == 1]):printf("Game Over%c"," \n"[1 == 1]);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/WX_1218639030/article/details/83187661
今日推荐