【题解】PAT 1007 Maximum Subsequence Sum

题目描述

原题链接:1007 Maximum Subsequence Sum
在这里插入图片描述

解题思路

读题,给出一个数组N,求这个数组的一个子序列,使得这个子序列的和最大
——很明显的动态规划问题
建立动态规划数组dp,其中dp[i]表示以元素N[i]结尾的子序列的最大和,则dp[i]=max(dp[i-1]+N[i], N[i])


同时,为了满足输出,在动态规划的同时还需要建立数组index记录子序列的开始元素下标,index[i]表示以N[i]结尾的最大和子序列的开始元素下标,做如下处理:
对于dp[i]而言,如果dp[i-1]>0,则index[i]=index[i-1], dp[i]=dp[i-1]+N[i]
否则index[i]=i, dp[i]=N[i]

注意还有特殊情况: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). 【如果有多个最大值序列,则输出i和j最小的】
PS:为了节省空间,本题采用滚动数组的方式

AC代码

#include <bits/stdc++.h>
using namespace std;
const int len = 1e5+1;
int N[len];

int main () {
    int k, dp=0, index=0; scanf("%d", &k);
    int ans=-1, ans_begin, ans_end;
    for (int i=0;i<k;i++) {
        scanf("%d", &N[i]);
        if (dp > 0) dp+=N[i];
        else {
            dp=N[i];
            index = i;
        }

        if (dp > ans) {
            ans=dp;
            ans_begin=index;
            ans_end=i;
        }
    }

    if (ans >= 0) printf("%d %d %d\n", ans, N[ans_begin], N[ans_end]);
    else printf("0 %d %d\n", N[0], N[k-1]);

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值