PAT1007刷题笔记-最大子序和

自己的写的代码不知道为啥有点小问题,第五个测试用例一直没通过,
但是按照题解改了一下max_sum的初始值为-1后直接就通过了。下面是按照题解修改后通过的代码:

#include <algorithm>
#include <cstring>
#include <cmath>
#include <ctime>
#include <fstream>
#include <iostream>
#include <istream>
#include <iterator>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <utility>
#include <vector>

using namespace std;
/*
 CLion 使用提示 :

  批量注释代码 => Ctrl + shift + /
  格式化代码   => option + command + L
  补全语句     => Shift + command + return
  生成构造器,getter和setter方法等 => control + return
  行注释       => control + /
  块注释       => control + shift + c
*/
#define  MAX 10000

void input(int N, int *a);

void output(int N, int *);

int main() {

    int N, a[MAX];
    scanf("%d", &N);
    input(N, a);
    output(N, a);

}

void input(int N, int *a) {
    for (int i = 0; i < N; ++i) {
        scanf("%d", &a[i]);
    }
}
/*
10
-1 -2 -3 -4 -5 -6 -7 -8 -9 -10
 */

/*
10
1 2 3 4 5 6 7 8 9 10
*/
//一直不知道咋记录max_begin,看的题解才知道是要用一个临时的下标记录以前
//子序和为负数的下一个位置的下标,然后在每次发现最大子序和之后就把max_left设置为之前记录的临时下标的位置,然后就可以准确记录最大子序和的初始下标了
void output(int N, int *a) {
    int sum = 0, max_sum = -1, max_begin = 0, max_end = N-1,temp=0;
    for (int i = 0; i < N; ++i) {
        sum += a[i];
        if (sum < 0) {
            sum = 0;
            temp=i+1;
        } else if (sum > max_sum) {
            max_sum = sum;
            max_begin=temp;
            max_end = i;
        }
    }
    if (max_sum<0) {
        max_sum=0;
        //max_begin=0;
        //max_end=N-1;
    }
    printf("%d %d %d", max_sum, a[max_begin], a[max_end]);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿维的博客日记

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值