【LeetCode】121. Best Time to Buy and Sell Stock
来源:互联网 发布:服务器开启80端口 编辑:程序博客网 时间:2024/06/03 04:09
问题描述
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: 0
In this case, no transaction is done, i.e. max profit = 0.
问题分析
动态规划问题
假设f(i)
是第i
天能拿到的最大利润,初始为0
;minPrice
是第i天之前的最低股价,初始为prices[0]
,也就是假设第一天就买入股票
到第i+1
天时,最大利润为f(i+1)
,则f(i+1)=max(f(i)
, prices[i+1]-minPrice)
,也就是如果今天的价格与之前的最低股价的差值比前一天的利润大,就采取新方案,也就在最低股价时买入,在今天卖出;否则就不动,继续持有股价,所以会有今天的最大利润=昨天的最高利润,即f(i+1) = f(i)
;然后更新最低股价,minPrice = min(prices[i+1], minPrice)
.
代码
class Solution {public: int maxProfit(vector<int>& prices) { if(prices.size()<=0) return 0; int f=0, f1=0; // f(i) 表示第 i 天时的最大利润,初始为0,此处f表示f(i), f1表示f(i-1) int buyPrice = prices[0]; // 之前买入的价格,假设第一天就买入 for(int i=1;i<prices.size();i++) { f1 = f = max(f1, prices[i]-buyPrice); buyPrice = min(prices[i], buyPrice); } return f; }};
0 0
- 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
- 121. Best Time to Buy and Sell Stock LeetCode
- [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
- 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
- 121.[Leetcode]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】11. Container With Most Water
- 1622-5 孔富晨 总结《2017年1月3日》 【连续第95天总结】
- 【Web前端】Linux下Sublime Text3的一些配置
- 端口转发
- DP (8) -- Is Subsequence,Ugly Number II
- 【LeetCode】121. Best Time to Buy and Sell Stock
- linux安装软件
- centOS 服务器操作 学习1
- javaWEB总结(17):cookie概述
- ALT+回车键 是强制换行的快捷键
- 1622-5 孔富晨 总结《2017年1月4日》 【连续第96天总结】
- c/c++指针常见错误
- SVN仓库迁移到其它机器
- linux 软硬链接