LeetCode学习篇十八——Best Time to Buy and Sell Stock with Cooldown

来源:互联网 发布:编译php扩展 编辑:程序博客网 时间:2024/05/18 00:13

题目:Say you have an array for which the ith 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]

难度:medium 通过率:39.2%

题目可画出有限状态图
这里写图片描述
图中有三个状态,箭头的指向表明了状态的转移过程,所以可以列出状态转移方程,假设第i天,则有:
f0[i] = max(f0[i-1], f2[i-1]);
f1[i] = max(f0[i-1]-prices[i], f1[i-1]);
f2[i] = f1[i-1] + prices[i];
可得代码如下,时间复杂度:O(n)

class Solution {public:    int maxProfit(vector<int>& prices) {        if(prices.size() <= 1 ) return 0;        vector<int> f0(prices.size());        vector<int> f1(prices.size());        vector<int> f2(prices.size());        f0[0] = 0;        f1[0] = -prices[0];        f2[0] = INT_MIN;        for(int i = 1; i < prices.size(); i++) {            f0[i] = max(f0[i-1], f2[i-1]);            f1[i] = max(f0[i-1]-prices[i], f1[i-1]);            f2[i] = f1[i-1] + prices[i];        }        return f0[prices.size() -1]>=f2[prices.size() -1] ? f0[prices.size() -1] : f2[prices.size() -1];    }};
1 0
原创粉丝点击