Best Time to Buy and Sell Stock with Cooldown
来源:互联网 发布:windows 2003 编辑:程序博客网 时间:2024/06/04 20:20
Say you have an array for which the ith element is the price of a given stock on dayi.
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 = 3transactions = [buy, sell, cooldown, buy, sell]
Solution 1:
class Solution {public: int maxProfit(vector<int>& prices) { int n = prices.size(); if (n < 2) { return 0; } int buf[n]; buf[0] = 0; for (int i = 1; i < n; i++) { buf[i] = buf[i-1]; for (int j = 0; j < i; j++) { int temp = 0; if (prices[i] > prices[j]) { temp += prices[i]-prices[j]; } if (j-2 >= 0) { temp += buf[j-2]; } buf[i] = max(buf[i], temp); } } return buf[n-1]; }};
Solution 2:
int maxProfit(vector<int>& p) { if (p.size() < 2) return 0; int i, sz = p.size(); int ret = 0; vector<int> buy(sz, 0); vector<int> sell(sz, 0); buy[0] = -p[0]; for (i = 1; i < sz; ++i) { sell[i] = max(buy[i - 1] + p[i], sell[i - 1] - p[i - 1] + p[i]); if (ret < sell[i]) //record the max sell[i] ret = sell[i]; if (1 == i) buy[i] = buy[0] + p[0] - p[1]; else buy[i] = max(sell[i - 2] - p[i], buy[i - 1] + p[i - 1] - p[i]); } return ret;}
0 0
- 309Best Time to Buy and Sell Stock with Cooldown
- leetcode Best 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
- LeetCode Best Time to Buy and Sell Stock with Cooldown
- Leetcode: Best Time to Buy and Sell Stock with Cooldown
- 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
- Best Time to Buy and Sell Stock with Cooldown
- LeetCode:Best Time to Buy and Sell Stock with Cooldown
- 309.Best Time to Buy and Sell Stock with Cooldown
- 309. Best Time to Buy and Sell Stock with Cooldown
- 309. Best Time to Buy and Sell Stock with Cooldown
- 309. Best Time to Buy and Sell Stock with Cooldown
- leetcode_309 Best Time to Buy and Sell Stock with Cooldown
- 309. Best Time to Buy and Sell Stock with Cooldown
- git
- AndroidStudio刚安装完新建项目之后就报错无法运行
- 常用SQL
- ThingWorx : 1、创建Thing
- linux 安装 eclipse 的靠谱步骤
- Best Time to Buy and Sell Stock with Cooldown
- CentOS yum 源的配置与使用
- display之block,inline,inline-block简单分析
- Android 开发规范与架构
- Spring事务管理学习
- iOS view中半透明,但是子控件透明度不受影响
- div的居中
- 免费创建微信公众号全攻略
- 【HTTP】http重定向301/302/303/307