码迷,mamicode.com
首页 > 其他好文 > 详细

数据结构 01-复杂度2 Maximum Subsequence Sum (25 分)

时间:2021-05-24 12:48:45      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:eth   must   inpu   stream   cas   seq   ext   style   最大子列和   

Given a sequence of K integers { N?1??, N?2??, ..., N?K?? }. A continuous subsequence is defined to be { N?i??, N?i+1??, ..., N?j?? } where 1ijK. 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

 

有一个不太符合常识的测试点

测试点6  最大子列和开始的几个数是0时, 也要计算入最大子列中     我以为的最大子列和.... 0不增加最大子列和 如果子列第一个数为0, 就不需要算入子列   结果卡了半天,还是要算入子列中才通过

 

解题思路

一边遍历一边计算 最大子列和

 

  当出现 当前的子列和 大于 已知的最大子列和 时

     更新最大子列和同时更新 子列开始和结尾下标 (结尾下标是子列开始下标+子列长度计数)

  当出现 当前子列和 小于 0时,  必须是小于0是才更新  

    重置最大子列和为0 , 子列长度计数为0, 子列开始下标为 当前下标+1 

 

还需要注意特殊输出格式 当序列全为负数的时候要判定 并 输出最大和0 和序列的第一个 最后一个数

#include <iostream>
using namespace std;
int main(){
    int n,temp,start{0},sum{0},max{-1},left{0},right{0},count{0};
    bool isAllNegative=true;
    cin >> n;
    int arr[n];
    for(int i=0;i<n;i++){
        scanf("%d",&temp);
        arr[i]=temp;
        sum+=temp;
        if(temp>=0){
            isAllNegative=false;
        }
        if(sum>max){
            max=sum;
            left=start;
            right=left+count;
        }
        count++;
        if(sum<0){//重置子列和 重置起点和计数
            sum=0;
            start=i+1;
            count=0;
        }
    }
    if(isAllNegative){
        cout<<"0"<<" "<< arr[0]<<" "<<arr[n-1]<<endl;
    }else{
        cout << max<<" "<< arr[left]<<" "<<arr[right]<<endl;
    }
    return 0;
}

 

数据结构 01-复杂度2 Maximum Subsequence Sum (25 分)

标签:eth   must   inpu   stream   cas   seq   ext   style   最大子列和   

原文地址:https://www.cnblogs.com/ichiha/p/14773954.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!