蒜厂年会
在蒜厂年会上有一个抽奖,在一个环形的桌子上,有 n n n 个纸团,每个纸团上写一个数字,表示你可以获得多少蒜币。但是这个游戏比较坑,里面竟然有负数,表示你要支付多少蒜币。因为这些数字都是可见的,所以大家都是不会出现的赔的情况。
游戏规则:每人只能抓一次,只能抓取一段连续的纸团,所有纸团上的数字和就是你可以获得的蒜币。
蒜头君作为蒜厂的一员在想,我怎么可以获得最多的蒜币呢?最多能获取多少蒜币呢?
因为年会是发奖,那么一定有大于 0 0 0 的纸团。
输入格式
第一行输入一个整数 n,表示有 n 个纸团。
第二行输入输入
n
n
n 个整数
a
i
a_i
ai,表示每个纸团上面写的数字(这些纸团的输入顺序就是环形桌上纸团的摆放顺序)。
输出格式
输出一个整数,表示蒜头君最多能获取多少蒜币。
数据范围
对于
30
%
30\%
30%的数据:
1
≤
n
≤
1
0
2
,
−
1
0
3
≤
a
i
≤
1
0
3
1 \le n \le 10^2, -10^3 \le a_i \le 10^3
1≤n≤102,−103≤ai≤103。
对于 60 % 60\% 60%的数据: 1 ≤ n ≤ 5 × 1 0 3 , − 1 0 6 ≤ a i ≤ 1 0 6 1 \le n \le 5×10^3, -10^6 \le a_i \le 10^6 1≤n≤5×103,−106≤ai≤106。
对于 100 % 100\% 100%的数据: 1 ≤ n ≤ 1 0 5 , − 1 0 9 ≤ a i ≤ 1 0 9 1 \le n \le 10^5, -10^9 \le a_i \le 10^9 1≤n≤105,−109≤ai≤109。
Sample Input
3
1 -2 1
Sample Output
2
这题是连续字串最大和的变种,这里变成了一个可以循环取的方式,那么依据题目的数据量来说如果对于每个情况都算一遍字串最大和,那么时间复杂度将达到 O ( n 2 ) O(n^2) O(n2) ,不出意外是超时的。那么此时我们其实可以发现,答案可以只分两类:①不越界取的最大值②越界取的最大值。(越界指取的途中会循环到开头)
对于①:这就是正常的也就是经典的连续字串最大和问题,直接用尺取法或者DP就能解决,这里假设解得答案为 a n s ans ans。
对于②:这里就需要一个转换,首先假设整个序列的和为 s u m sum sum,中间未取的部分的和为 m i d mid mid 。任何一个会越界的情况的答案就一定等于 s u m − m i d sum - mid sum−mid。然而 s u m sum sum 是一个定值,所以我们只要取mid的最小值,那么显然, m i d mid mid 是一个连续字串的和,所以我们只要用连续字串最大和的方法同理求最小,求得 m i d mid mid ,此种情况的答案就是 s u m − m i d sum - mid sum−mid。
最终答案就等于
m
a
x
(
a
n
s
,
s
u
m
−
m
i
d
)
max(ans, sum - mid)
max(ans,sum−mid), 整体时间复杂度为
O
(
n
)
O(n)
O(n) 。
DP法相对于尺取法来说虽然消耗更多空间,但可能代码实现起来会更快。
尺取:
#include <iostream>
#include <cstdio>
using namespace std;
typedef long long ll;
ll a[100005];
ll now;
ll ans;
ll ans1;
ll sum;
int main() {
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
int n;
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
scanf("%lld", &a[i]);
sum += a[i];
}
for (int i = 0; i < n; i++) {
if (a[i] > 0) {
now = 0;
while(i < n) {
if (now + a[i] < 0) break;
now += a[i];
if (now > ans) ans = now;
i++;
}
}
}
for (int i = 0; i < n; i++) {
if (a[i] < 0) {
now = 0;
while(i < n) {
if (now + a[i] > 0) break;
now += a[i];
if (now < ans1) ans1 = now;
i++;
}
}
}
printf("%lld", max(ans, sum - ans1));
}
DP:
#include <iostream>
#include <cstdio>
using namespace std;
typedef long long ll;
ll a[100005];
ll dp[100005];
ll sum;
ll Max, Min = 1e18;
int main() {
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
int n;
scanf("%d", &n);
for (int i = 1; i <= n; ++i) {
scanf("%lld", &a[i]);
sum += a[i];
}
for (int i = 1; i <= n; ++i) {
if (dp[i - 1] > 0) dp[i] = dp[i - 1] + a[i];
else dp[i] = a[i];
Max = max(Max, dp[i]);
}
for (int i = 1; i <= n; ++i) {
if (dp[i - 1] < 0) dp[i] = dp[i - 1] + a[i];
else dp[i] = a[i];
Min = min(Min, dp[i]);
}
printf("%lld", max(Max, sum - Min));
}