leetcode 309 best time to sell or buy stock
来源:互联网 发布:看电视直播软件 编辑:程序博客网 时间:2024/06/05 23:59
本题采用动态规划
首先,我们知道,股票可分为两个状态,卖出状态和买入状态
未持股状态包含在第i天的时候,股票处于sell状态或者处于冷却期,即cool.处于冷却期,利润为sell【i-1】,处于sell状态,利润为buy【i-1】+prices【i】
买入状态包含在第i天,股票处于buy状态或者前一天处于买入状态,若今天买入,由于前一天不可卖出,则利润为sell【i-2】-prices【i】,若不是今天买入,则利润为buy【i-1】
分别取最大值,就是今天持股和未持股最大利润。
如下
sell[i] = Math.max(sell[i-1], buy[i-1]+prices[i]);
buy[i] = Math.max(buy[i-1], sell[i-2]-prices[i]);
当然,获取最大利润时最后一天必然是卖出状态,返回值为sell【prices.length-1】
代码如下
class Solution { public int maxProfit(int[] prices) { if(prices==null||prices.length<=1)return 0;int buy[] = new int[prices.length];int sell[] = new int[prices.length];sell[0] = 0;buy[0] = -prices[0]; buy[1] = Math.max(buy[0], -prices[1]);; sell[1] = Math.max(prices[1]-prices[0],sell[0]);//由于不能定义sell[-1],只能这样写for (int i = 2; i < prices.length; i++) {sell[i] = Math.max(sell[i-1], buy[i-1]+prices[i]);buy[i] = Math.max(buy[i-1], sell[i-2]-prices[i]);}return sell[prices.length-1]; }}
阅读全文
0 0
- leetcode 309 best time to sell or buy stock
- 【LeetCode】Best Time to Buy and Sell Stock & Best Time to Buy and Sell Stock
- [LeetCode] [LeetCode]Best Time to Buy and Sell Stock
- LeetCode--Best Time to Buy and Sell Stock (贪心策略 or 动态规划)
- 【LeetCode with Python】 Best Time to Buy and Sell Stock
- [LeetCode]Best Time to Buy and Sell Stock
- [LeetCode]Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock
- LeetCode Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock III
- Leetcode: Best time to buy and sell a stock I
- Leetcode: Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock III
- [Leetcode] Best Time to Buy and Sell Stock
- [Leetcode] Best Time to Buy and Sell Stock II
- [Leetcode] Best Time to Buy and Sell Stock III
- LeetCode : Best Time to Buy and Sell Stock II
- [leetcode] Best Time to Buy and Sell Stock
- Android中获取正在运行的服务
- 使用ssh-keygen生存密钥对
- urlopen error [errno 10060]的解决思路
- TabLayout
- 微信小程序开发常见问题分析
- leetcode 309 best time to sell or buy stock
- 数据仓库简介---概况
- 高性能MYSQL——6章查询执行的基础(1)
- Android 获取验证码倒计时实现
- EditText限制输入表情,限制输入字数长度
- String、StringBuffer、StringBuilder的区别
- Java数据结构与算法解析(十四)——二叉堆
- hadoop入门之利用hadoop来对文档数据归类统计案例wordcount
- unity computshader的入门教程,别听半灌水瞎BB。