Leetcode: 309. Best Time to Buy and Sell Stock with Cooldown 有冷却机制的最优炒股问题

Leetcode: 309. Best Time to Buy and Sell Stock with Cooldown 有冷却机制的炒股问题

问题描述

Say you have an array for which the i -th element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:

  • You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
  • After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)

Example:

prices = [1, 2, 3, 0, 2]
maxProfit = 3
transactions = [buy, sell, cooldown, buy, sell]

可以无限次的买卖,但是必须卖了之后才能再买,而且卖了之后必须冷却一天(当天不能再买入)。

本题(传送门)是炒股问题 Best Time to Buy and Sell Stock(传送门)的一个变种,该系列还有II、III、IV。

解决方案

这里用有限状态自动机(Finite State Automaton),我们设计三种状态:

名称状态类型描述
A起始状态,可终止手上没有股票且可以买入
B非终止状态持有股票,可以卖出也可以休息一天,不能买入
C可终止状态刚刚卖掉股票之后的状态,不持有股票但还不能买

这里写图片描述
对于每一天,计算处于A/B/C状态下最高的利润分别是多少。返回最后一天A和C状态下利润的较大值。

class Solution {
public:
	int maxProfit(vector<int>& prices) {
		if (prices.empty())  return 0; 
		int n = prices.size();
		if (n == 1)    return 0;
		vector<int> A(n, 0), B(n, 0), C(n, 0);
		A[0] = 0;
		B[0] = -prices[0];
		C[0] = INT_MIN;
		for (int i = 1; i<n; i++){
			// A状态休息一天,或者C状态休息一天,则进入A状态
			A[i] = max(A[i - 1], C[i - 1]); 
			// B状态休息一天,或者A状态买入股票,则进入B状态
			B[i] = max(B[i - 1], A[i - 1] - prices[i]);
			// B状态卖出股票后,进入C状态
			C[i] = B[i - 1] + prices[i];
		}
		return max(A[n - 1], C[n - 1]);
	}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值