HDU - 1003 Max Sum 【DP】

本文介绍了一个经典的编程问题——最大子序列和问题,并提供了一段C++代码实现。该问题要求从给定序列中找到和最大的连续子序列及其位置。文章通过O(N)的时间复杂度解决此问题,并特别注意了当所有输入为负数的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

http://acm.hdu.edu.cn/showproblem.php?pid=1003

题意
给出一个序列 要求找出一个和最大的子序列

思路
O(N)的做法 但是要标记 子序列的头部位置
如果输入全部是负数的话 应该输出是最小的负数和它的位置 而不是输出0 0 0

AC代码

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<vector>
#include<map>
#include<set>
#include<string>
#include<list>
#include<stack>
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const int maxn = 1e5 + 5;


int main()
{
    int t;
    cin >> t;
    int count = 1;
    while (t--)
    {
        int n;
        scanf("%d", &n);
        int num;
        int flag = 1;
        int tot = 0;
        int ans = -1000;
        int start = 0, end = 0;
        for (int i = 1; i <= n; i++)
        {
            scanf("%d", &num);
            tot += num;

            if (tot > ans)
            {
                ans = tot;
                start = flag;
                end = i;
            }
            if (tot < 0)
            {
                tot = 0;
                flag = i + 1;
            }
        }
        printf("Case %d:\n", count++);
        printf("%d %d %d\n", ans, start, end);
        if (t != 0)
            cout << endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值