股票买卖Ⅴ

给定一个长度为N数组,数组中的第i个数字表示一个给定股票在第i天的价格。
设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票)∶
        你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
        卖出股票后,你无法在第二天买入股票(即冷冻期为1天).
输入格式
第一行包含整数N,表示数组长度。
第二行包含N个不超过10000的正整数,表示完整的数组。
输出格式
输出一个整数,表示最大利润。
数据范围
1≤N ≤ 1e5
输入样例:

5
1 2 3 0 2


输出样例:

3


样例解释
对应的交易状态为: [买入,卖出,冷冻期,买入,卖出],第一笔交易可得利润2-1=1,第二笔交易可得利润2-0=2,共得利润1+2 = 3。
 

dp[i][0] 表示第i天卖出可以获得的收益 dp[i][0] = dp[i - 1][1] + w[i]

dp[i][1] 表示第i天有货,可以从 第 i - 1 天有货和第 i 天买(第 i - 1 天为冷静期)dp[i][1] = max(dp[i - 1][2] - w[i], dp[i - 1][1])

dp[i][2] 表示第i天为无货且不是第i天卖出去的,可以从本来就无货或者第 i - 1 天卖出去的转移 dp[i][2] = max(dp[i - 1][2], dp[i - 1][0])

#include<bits/stdc++.h>
using namespace std; using ll = long long;
int dir[4][2] = { 1, 0, -1, 0, 0, 1, 0, -1 };
//using lll = __int128;template <class T>istream& read(T& x, istream& cin = std::cin);template <class T>ostream& write(T x, ostream& cout = std::cout);ostream& operator<<(ostream& cout, lll x);istream& operator>>(istream& cin, lll &x);
bool check(int i, int j);

const int N = 1e5 + 10, mod = 1e9 + 7, INF = 0x3f3f3f3f;

int n, m, dp[N][3], w[N];

void init() {
	dp[0][1] = dp[0][0] = -INF;
	dp[0][2] = 0;
	cin >> n;
	for (int i = 1; i <= n; i++) {
		cin >> w[i];
	}
	//	cout << "初始化完成\n";
	return;
}

void dfs(int u) {
	if (!u) return;
	dfs(u - 1);
	dp[u][0] = dp[u - 1][1] + w[u];  // 第 u 天卖出,只能从前一天有货的状态转移
	dp[u][1] = max(dp[u - 1][1], dp[u - 1][2] - w[u]);  // 第 u 天有货,可以从第 u - 1 天无货转移
	dp[u][2] = max(dp[u - 1][2], dp[u - 1][0]);// 第 u 天无货
}

void solve() {
	dfs(n);
	cout << max(dp[n][2], dp[n][0]);
	return;
}

int main(void) {
	ios::sync_with_stdio(0); cin.tie(0); cout << setprecision(6) << fixed;//保留6位小数从小数点后计数
	int TT = 1;
	//cin >> TT;
	for (int ii = 0; ii < TT; init(), solve(), ii++, cout << "\n") {}
	return 0;
}
//template <class T> istream& read(T& x, istream& cin) {T num = 0; bool f = 0; char ch = 0;while (!isdigit(ch)) { f |= ch == '-'; if (!cin.get(ch)) return cin; }while (isdigit(ch)) { num = (num << 3) + (num << 1) + (ch ^ 48); if (!cin.get(ch)) return cin; }x = f ? -num : num; return cin;}template <class T> ostream& write(T x, ostream& cout) {if (x < 0) cout.put('-'), x = -x;if (x > 9) write(x / 10);cout.put(x % 10 + '0'); return cout;}ostream& operator<<(ostream& cout, lll x) {write(x);return cout;}istream& operator>>(istream& cin, lll &x) {return read(x);}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值