PAT A1007 最大子列和

求最大子列和的几种方法:https://blog.csdn.net/he626shidizai/article/details/88378773

注意事项

写这道题的时候才意识到审题是多么的重要,最前面的分析错了,后面怎么都不会对的。改了好多次才成功,而且还只能打补丁。输出有很多需要注意的点:

  • output the one with the smallest indices i and j (as shown by the sample case)----也就是说 如果子列是 0 0 1 2 3 的情况,那么子列的第一个元素是0而不是1
  • 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.-----如果出现负数和0混在一起的情况,那么最大子列就是0的序列 如:-1 -1 0 输出的结果就应该是 0 0 0

代码

#include<stdio.h>

int main(){
  int k;

  scanf("%d",&k);
  int *a = new int[k];
  for(int i = 0; i < k; i ++)
    scanf("%d",&a[i]);

  int max_sum = -1;		//当前最大子列和
  int this_sum = 0;		//当前子列和
  int sub_left = 0;		//当前子列的最左下标
  int left = 0;			//最大和子列的最左下标		
  int right = k-1;		//最大和子列的最右下标

  for(int i = 0;i < k; i ++){
    this_sum += a[i];
    if(this_sum > max_sum){
      max_sum = this_sum;
      left = sub_left;
      right = i;
    }
    else if(this_sum < 0){
        this_sum = 0;
        sub_left = i + 1;
    }
  }
  if(max_sum >= 0)
    printf("%d %d %d",max_sum, a[left], a[right]);
  else			//全部是负数的情况
    printf("%d %d %d",0, a[0], a[k-1]);
  delete []a;
  return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值