AcWing1057 - 股票买卖IV
给定一个长度为 N 的数组,数组中的第 i 个数字表示一个给定股票在第 i 天的价格。
设计一个算法来计算你所能获取的最大利润,你最多可以完成 k 笔交易。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。一次买入卖出合为一笔交易。
输入格式
第一行包含整数 N 和 k,表示数组的长度以及你可以完成的最大交易笔数。
第二行包含 N 个不超过 10000 的非负整数,表示完整的数组。
输出格式
输出一个整数,表示最大利润。
数据范围
1≤N≤105, 1≤k≤100
输入样例1:
1
2
3 2
2 4 1
输出样例1:
1
2
输入样例2:
1
2
6 2
3 2 6 5 0 3
输出样例2:
1
7
样例解释
样例1:在第 1 天 (股票价格 = 2) 的时候买入,在第 2 天 (股票价格 = 4) 的时候卖出,这笔交易所能获得利润 = 4-2 = 2 。
样例2:在第 2 天 (股票价格 = 2) 的时候买入,在第 3 天 (股票价格 = 6) 的时候卖出, 这笔交易所能获得利润 = 6-2 = 4 。随后,在第 5 天 (股票价格 = 0) 的时候买入,在第 6 天 (股票价格 = 3) 的时候卖出, 这笔交易所能获得利润 = 3-0 = 3 。共计利润 4+3 = 7.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <cstring>
using namespace std;
const int N = 100010, M = 110;
int n, m;
int w[N];
int f[N][M][2];
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) scanf("%d", &w[i]);
memset(f, 0xcf, sizeof f);
for (int i = 0; i <= n; i++) f[i][0][0] = 0;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++) {
f[i][j][0] = max(f[i - 1][j][0], f[i - 1][j][1] + w[i]);
f[i][j][1] = max(f[i - 1][j][1], f[i - 1][j - 1][0] - w[i]);
}
int res = 0;
for (int i = 0; i <= m; i++) res = max(res, f[n][i][0]);
printf("%d\n", res);
return 0;
}
可以化简一维(滚动数组)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <cstring>
using namespace std;
const int N = 100010, M = 110;
int n, m;
int w[N];
int f[M][2];
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) scanf("%d", &w[i]);
memset(f, 0xcf, sizeof f);
f[0][0] = 0;
for (int i = 1; i <= n; i++)
for (int j = m; j >= 1; j--) {
f[j][0] = max(f[j][0], f[j][1] + w[i]);
f[j][1] = max(f[j][1], f[j - 1][0] - w[i]);
}
int res = 0;
for (int i = 0; i <= m; i++) res = max(res, f[i][0]);
printf("%d\n", res);
return 0;
}
This post is licensed under CC BY 4.0 by the author.