求一个区间内连续两段不相交区间最大和。

// File Name: 2479.cpp
// Author: Missa_Chen
// Created Time: 2013年06月22日 星期六 16时19分02秒

#include <iostream>
#include <string>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <queue>
#include <map>
#include <stack>
#include <set>
#include <cstdlib>

using namespace std;

#define LL long long
const int inf = 0x3f3f3f3f;
const int maxn = 5e4 + 5;
int n;
int num[maxn], st[maxn], end[maxn];
int main()
{
	int cas;
	scanf("%d", &cas);
	while (cas --)
    {
		scanf("%d", &n);
		for (int i = 1; i <= n; ++i)
			scanf("%d", &num[i]);
		for (int i = 0; i <= n + 1; ++i)
			st[i] = end[i] = -inf;
		int tmp = -inf, ans = -inf;
		for (int i = 1; i <= n; ++i)
		{
			if (tmp >= 0)
				tmp += num[i];
			else
				tmp = num[i];
			end[i] = max(end[i - 1], tmp);
		}
		tmp = -inf;
		for (int i = n; i >= 1; --i)
		{
			if (tmp >= 0)
				tmp += num[i];
			else
				tmp = num[i];
			st[i] = max(st[i + 1], tmp);
		}
		for (int i = 1; i < n; ++i)
			ans = max(ans, end[i] + st[i + 1]);
		printf("%d\n", ans);
    }
    return 0;
}

  

相关文章:

  • 2022-01-20
  • 2021-07-09
  • 2022-12-23
  • 2021-10-19
  • 2021-07-28
  • 2021-05-22
  • 2022-02-17
  • 2021-12-10
猜你喜欢
  • 2022-12-23
  • 2021-09-08
  • 2021-05-26
  • 2022-01-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案