循环数组的最大子段和

版权声明:iQXQZX https://blog.csdn.net/Cherishlife_/article/details/85021196

假·最大子段和

Time Limit: 1000 ms Memory Limit: 65536 KiB

Submit Statistic

Problem Description

给出一个数组,数组首尾相连,询问最大连续子段和为多少。

Input

首先输入一个T表示T (1<=T<=50) 组数据,然后每组数据首先输入一个n (1<=n<=1e5) 表示有n个数字,然后输入n个数字(题目保证数字范围在 int 内),表示所求数组。

Output

数组最大的连续子段和。

Sample Input

1
7
10 -100 1 -2 -5 3 4

Sample Output

17

Hint

全是负数的时候,最大的连续子段和为 0。

Source

分析:本题与普通的最大子段和问题不同的是,最大子段和可以是首尾相接的情况,即可以循环。那么这个题目的最

     大子段和有两种情况

    (1)正常数组中间的某一段和最大。这个可以通过普通的最大子段和问题求出。

    (2)此数组首尾相接的某一段和最大。这种情况是由于数组中间某段和为负值,且绝对值很大导致的,那么我们只需要把中间的和为负值且绝对值最大的这一段序列求出,用总的和减去它就行了。

     即,先对原数组求最大子段和,得到ans1,然后把数组中所有元素符号取反,再求最大子段和,得到ans2,

     原数组的所有元素和为ans,那么最终答案就是 max(ans1, ans + ans2)。

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
int a[100005];

LL make(int a[], int n)
{
    LL ans = 0;
    LL sum = 0;
    for (int i = 0; i < n; i++)
    {
        sum += a[i];
        ans = max(ans, sum);
        if (sum < 0)
            sum = 0;
    }
    return ans;
}
int main()
{
    int n, t;
    scanf("%d", &t);
    while (t--)
    {
        scanf("%d", &n);
        LL ans = 0;
        for (int i = 0; i < n; i++)
        {
            scanf("%d", &a[i]);
            ans += a[i];
        }
        
        LL ans1 = make(a, n);
        for (int i = 0; i < n; i++)
            a[i] = -a[i];

        LL ans2 = make(a, n);
        ans = max(ans + ans2, ans1);
        printf("%lld\n", ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Cherishlife_/article/details/85021196