LeetCode题解:121. Best Time to Buy and Sell Stock
来源:互联网 发布:java框架是什么意思 编辑:程序博客网 时间:2024/05/19 02:42
原题地址
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Example 1:
Input: [7, 1, 5, 3, 6, 4]Output: 5max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2:
Input: [7, 6, 4, 3, 1]Output: 0In this case, no transaction is done, i.e. max profit = 0.
简单的动态规划问题:
思路1:
public class Solution { public int maxProfit(int[] prices) { int minPrice = Integer.MAX_VALUE, maxPro = 0; for (int price : prices) { minPrice = Integer.min(price, minPrice); maxPro = Integer.max(maxPro, price - minPrice); } return maxPro; }}
思路2:
设buy[i]表示第i天 手里仍有未卖出的股票 最大利润。sell[i]表示第i天手里已经没有未卖出的股票 获得的最大利润。
状态转移方程为:
buy[i] = max{buy[i-1],-prices[i-1]} , i>=1&&i<=n
sell[i] = max{sell[i-1],buy[i]+prices[i-1]} i>=1&&i<=n
其中buy[i]的作用相当于在前i天中选一个价格最小的,这样有可能会获得最大利润。
但是光买的时候价格最低没有用,需要两天的价格差值最大才可以。比如 价格序列为5,10,1,2 这样的话,价格最低的是1,1后面只有2了,所以得到的最大利润是1,显然是错误的。
所以需要sell来控制最大的差值,buy会更新成最小的价格,但是更新了不一定会有用,最后由sell来控制最大的差值。
但是sell和buy的更新只用到了前一天的数据,所以优化成如下:
buy = max{buy,-prices[i-1]}
sell = max{sell,buy+prices[i-1]} i>=1&&i<=n
public class Solution { public int maxProfit(int[] prices) { int buy = Integer.MIN_VALUE, sell = 0; for (int price : prices) { buy = Integer.max(buy, -price); sell = Integer.max(sell, buy + price); } return sell; }}
- LeetCode题解:121. Best Time to Buy and Sell Stock
- Leetcode题解 121. Best Time to Buy and Sell Stock
- 【LeetCode题解】121. Best Time to Buy and Sell Stock
- LeetCode题解:121. Best Time to Buy and Sell Stock
- LeetCode 121. Best Time to Buy and Sell Stock & 122. 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
- LeetCode题解:Best Time to Buy and Sell Stock II
- LeetCode 121 Best Time to Buy and Sell Stock题解
- 【动态规划】Leetcode编程题解:121. Best Time to Buy and Sell Stock Add to List
- LeetCode 121. Best Time to Buy and Sell Stock
- [Leetcode] 121. Best Time to Buy and Sell Stock
- [leetcode] 121. Best Time to Buy and Sell Stock
- 【leetcode】121. Best Time to Buy and Sell Stock
- [leetcode] 121. Best Time to Buy and Sell Stock
- PHP伪造IP或来源地址
- Android -- Android.mk简介
- 彻底删除SVN版本库某一文件夹或文件
- 51Nod-2000-四边形分割平面
- 真实可用selenium3.5.0+python3.6.3环境搭建
- LeetCode题解:121. Best Time to Buy and Sell Stock
- eclipse spring环境搭建
- AutoCAD .Net 绘制临时图形
- java validation 后台参数验证
- unity+action使用函数作为传参(匿名函数)
- js浏览器截图
- 2017-12-10战斗有限状态机FSM
- 小学期实践
- Ciclop开源3D扫描仪软件---Horus源码分析之point_cloud_roi.py