顺序表应用8:最大子段和之动态规划法

顺序表应用8:最大子段和之动态规划法

Time Limit: 5MS  Memory Limit: 500KB
Problem Description

 给定n(1<=n<=100000)个整数(可能为负数)组成的序列a[1],a[2],a[3],…,a[n],求该序列如a[i]+a[i+1]+…+a[j]的子段和的最大值。当所给的整数均为负数时定义子段和为0,依此定义,所求的最优值为: Max{0,a[i]+a[i+1]+…+a[j]},1<=i<=j<=n。 例如,当(a[1],a[2],a[3],a[4],a[5],a[6])=(-2,11,-4,13,-5,-2)时,最大子段和为20。

 

注意:本题目要求用动态规划法求解,只需要输出最大子段和的值。

Input

第一行输入整数n(1<=n<=100000),表示整数序列中的数据元素个数;

第二行依次输入n个整数,对应顺序表中存放的每个数据元素值。

Output

输出所求的最大子段和

 

Example Input
6
-2 11 -4 13 -5 -2
Example Output
20
Hint

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <cstdlib>
#define Maxsize 100000
using namespace std;

typedef int element;
typedef struct
{
    element *elem;
    int length;
    int listsize;
} Sqlist;

int InitList(Sqlist &L)
{
    L.elem = new element[Maxsize];
    if(!L.elem)
        return -1;
    L.length = 0;
    L.listsize = Maxsize;
    return 1;
}

void creat(Sqlist &L, int n)
{
    for(int i = 0; i < n; i++)
    {
        scanf("%d", &L.elem[i]);
        L.length++;
    }
}

int Msub(Sqlist &L, int n)
{
    int ThisMax=0;
    int SumMax=0;
    for(int i = 0; i < n; i++)
    {
        ThisMax += L.elem[i];
        if(ThisMax > SumMax)
            SumMax = ThisMax;
        else if(ThisMax < 0)
            ThisMax = 0;
    }
    return SumMax;
}

int main()
{
    Sqlist L;
    int n;
    cin >> n;
    InitList(L);
    creat(L, n);
    cout << Msub(L, n) << endl;
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值