zoukankan      html  css  js  c++  java
  • PAT 1007 Maximum Subsequence Sum 最大连续子序列和

    Given a sequence of K integers { N1, N2, …, NK }. A continuous subsequence is defined to be { Ni, Ni+1, …,Nj } where 1 <= i <= j <= K. The Maximum Subsequence is the continuous subsequence which has thelargest 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 themaximum 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
     
    题目意思:求最⼤连续⼦序列和,输出最⼤的和以及这个⼦序列的开始值和结束值。如果所有数都⼩于0,那么认为最⼤的和为0,并且输出⾸尾元素。
    解题思路:最开始的思路就是直接两层循环,设置i和j两个指针直接来定位求和,但是后来发现,其实可以直接使用一层循环,因为所求的和一般情况下必然是正数,除非全都是负数。但如果一开始就将全是负数的情况剔除后,只用一层循环便可以,一旦求和的结果是负数,那么起始定位的指针i便从其后重新取。
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    #define inf 0x7fffffff
    using namespace std;
    
    int a[10010];
    int main()
    {
        int n,i,left,right,ans=0,l=1;
        int maxs=-inf;
        int flag=0;
        scanf("%d",&n);
        for(i=1; i<=n; i++)
        {
            scanf("%d",&a[i]);
            if(a[i]>=0)
            {
                flag=1;
            }
        }
        if(flag==0)//全部为负数的情况
        {
            printf("%d %d %d
    ",ans,a[1],a[n]);
            return 0;
        }
        for(i=1; i<=n; i++)
        {
            ans+=a[i];
            if(ans<0)
            {
                ans=0;
                l=i+1;
            }//直到连续子序列出现正数
            else if(ans>maxs)//更新最大连续子序列
            {
                maxs=ans;
                left=l;
                right=i;
            }
        }
        printf("%d %d %d
    ",maxs,a[left],a[right]);
        return 0;
    }
  • 相关阅读:
    机器学习之决策树与随机森林模型
    深度学习入门篇--手把手教你用 TensorFlow 训练模型
    Android 性能测试之方向与框架篇
    机器学习:从入门到第一个模型
    5分钟教你玩转 sklearn 机器学习(上)
    Hbase 技术细节笔记(上)
    五年 Web 开发者 star 的 github 整理说明
    腾讯云发布第三代云服务器矩阵,开放更强计算力赋能产业智能化
    为什么要用深度学习来做个性化推荐 CTR 预估
    云 MongoDB 优化让 LBS 服务性能提升十倍
  • 原文地址:https://www.cnblogs.com/wkfvawl/p/11068627.html
Copyright © 2011-2022 走看看