[LeetCode]Best Time to Buy and Sell Stock
来源:互联网 发布:网络蔬菜超市 编辑:程序博客网 时间:2024/06/13 20:20
今天写的题目是Best Time to Buy and Sell Stock,之前写过它的II版本,但是是用贪婪算法,这次写的是用动态规划
121Best Time to Buy and Sell Stock40.4%Easy题目要求是这样的: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.
输入是一个数组,里面的值代表第i天stock能买入/卖出的价格,你只能买入并卖出一次,并且只能先买入后再卖出,要求的是什么时候买入卖出能得到最大收益。
题目看似很简单,但是我们并不知道我们在买入时是否之后存在价格更低的时候可以买入获得更大收益,如果有,又不能保证在之后有更好的卖出价使得收益比原来的选择更好。因此我们需要动态规划。当我们找到第一个 prices[i]<prices[i+1] 时,假设我们买入,当然只是假设,并不是最终确定的买入的时间,之后只要存在prices[i]>prices[buy],那么我们计算差价,取最大值作为最终收益。当然,如果之后出现更低的买入价,我们再假设此时为新的买入时间buy_2,如果出现了prices[i]-prices[buy]>profit,自然也有prices[i]-prices[buy_2]>profit,此时差价就是新的收益了,如果一直没有prices[i]-prices[buy_2]>profit,那么说明没有合适的卖出时间使得收益更高,原来的profit就是最大收益。
代码如下:
int maxProfit(vector<int>& prices) {if(prices.size()==0){ return 0;}int profit=0;int buy=0;int sell=0;for(int i=0;i<prices.size()-1;i++){ if(prices[i]<prices[i+1]) { profit=prices[i+1]-prices[i]; buy=i; break; }}int j=buy+1;while(j<prices.size()){ if(profit<prices[j]-prices[buy]) { profit=prices[j]-prices[buy]; } if(prices[j]<prices[buy]) { buy=j; } j++;}return profit;}
- 【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 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
- leetcode 16: Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock
- 打印10000以内的回文数字
- Spring mvc 视图解析器 ContentNegotiatingViewResolver 源码分析
- maven打包时候将依赖jar包打入
- 运维-JVM监控之线程问题
- SMA、SMB、SMC封装的二极管尺寸区分
- [LeetCode]Best Time to Buy and Sell Stock
- 1089. Insert or Merge 解析
- Linux查看系统信息的一些命令及查看已安装软件包的命令
- 水体提取方法之单波段阈值法升级版
- Same Tree
- JPEG文件格式
- HashMap的用法(两种迭代方法案例)
- Handler编写调试
- 读书笔记--迪米特法则