309. Best Time to Buy and Sell Stock with Cooldown
2016-03-21 10:42
337 查看
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:
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
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]
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
public class Solution { public int maxProfit(int[] prices) { int sell = 0, prev_sell = 0, buy = Integer.MIN_VALUE, prev_buy; for (int price : prices) { prev_buy = buy; buy = Math.max(prev_sell - price, prev_buy); prev_sell = sell; sell = Math.max(prev_buy + price, prev_sell); } return sell;} }
相关文章推荐
- Linux 杂记
- PHP数组格式的所有名族代码和名称
- MyEclipse8.5添加tomcat7
- php进阶:正则表达式的搜索和替换
- warning: incompatible implicit declaration of built-in function ‘strlen’
- 机器学习笔记—生成学习
- Tomcat开机自启动
- ARP地址解析协议
- smarty section循环
- smarty 入门
- absolute与relative怎么区分,
- Warning: Cannot modify header information - headers already sent by....
- 2013年03月21日
- stdClass是PHP的一个基类
- PHP正则表达式 /i, /is, /s, /isU等
- 关于PHP5 Session生命周期介绍
- MySql查询结果按照指定顺序排序
- <meta http-equiv=...> 的功能
- Smarty模板中变量修饰格式: {$var|方法1:参数1:参数2…|方法2…}
- php curl_init函数用法