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]; }};
- LeetCode学习篇十八——Best Time to Buy and Sell Stock with Cooldown
- leetcode Best Time to Buy and Sell Stock with Cooldown
- LeetCode Best Time to Buy and Sell Stock with Cooldown
- Leetcode: Best Time to Buy and Sell Stock with Cooldown
- [LeetCode]Best Time to Buy and Sell Stock with Cooldown
- Leetcode Best Time to Buy and Sell Stock with Cooldown
- leetcode - Best Time to Buy and Sell Stock with Cooldown
- LeetCode:Best Time to Buy and Sell Stock with Cooldown
- leetcode Best Time to Buy and Sell Stock with Cooldown
- Leetcode Best Time to Buy and Sell Stock with Cooldown
- LeetCode:Best Time to Buy and Sell Stock with Cooldown
- LeetCode--Best Time to Buy and Sell Stock with Cooldown
- leetcode——309——Best Time to Buy and Sell Stock with Cooldown
- Leetcode算法学习日志-309 Best Time to Buy and Sell Stock with Cooldown
- 309Best Time to Buy and Sell Stock with Cooldown
- Best Time to Buy and Sell Stock with Cooldown
- Leetcode197: Best Time to Buy and Sell Stock with Cooldown
- Best Time to Buy and Sell Stock with Cooldown
- TypeHandler的实例...
- 基于MeanShift的目标跟踪算法及实现
- 一起来写web server 04 -- 线程池版本
- 39级台阶
- Android mvp
- LeetCode学习篇十八——Best Time to Buy and Sell Stock with Cooldown
- hdu_1671 Phone List(字典树)
- php 语法风格切换 自学第1天
- UE4 粒子系统问题 no fixed bounding box
- 停止win10自动更新
- 网易2017实习生笔试7
- 硬盘模式IDE和AHCI
- linux笔记
- PMP学习笔记之第三章 项目管理过程