Maximum sum 二维最大子段和

该博客主要介绍如何计算给定二维数组A的最大子段和d(A),其中A包含n个整数,且n的范围在2到50000之间,每个数的绝对值不超过10000。内容包括输入输出格式说明及样例测试用例。

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

Given a set of n integers: A={a1, a2,..., an}, we define a function d(A) as below:

Your task is to calculate d(A).

Input

The input consists of T(<=30) test cases. The number of test cases (T) is given in the first line of the input.
Each test case contains two lines. The first line is an integer n(2<=n<=50000). The second line contains n integers: a1, a2, ..., an. (|ai| <= 10000).There is an empty line after each case.

Output

Print exactly one line for each test case. The line should contain the integer d(A).

Sample Input

1

10
1 -1 2 2 3 -3 4 -4 5 -5

Sample Output

13
lv[i]表示以第i个元素为连续序列最后一个元素时的最大和;rv[i]表示以第i个元素为连续序列第一个元素时的最大和
mav[i]为倒数i个元素中最大连续子段和

 

#include<iostream>
#include<cstdio>
using namespace std;
#define inf INT_MIN
int a[50010],lv[50010],rv[50010],mav[50010];
int main()
{
    int t;cin>>t;
    while(t--)
    {
        int n;
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
        }
        lv[1]=a[1];rv[n]=a[n];
        for(int i=2;i<=n;i++)
        {
            lv[i]=max(lv[i-1]+a[i],a[i]);
        }
        for(int i=n-1;i>=1;i--)
        {
            rv[i]=max(a[i],a[i]+rv[i+1]);
        }
        mav[n]=a[n];
        for(int i=n-1;i>=1;i--)
        {
            mav[i]=max(rv[i],mav[i+1]);///对于最后i个元素组成的序列,第i个元素是最大连续子串中的元素或不是这两种状态
        }
        int ans=inf;
        for(int i=2;i<=n;i++)
        {
            ans=max(ans,lv[i-1]+mav[i]);
        }
        printf("%d\n",ans);
        }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值