[leetcode] 121. Best Time to Buy and Sell Stock
来源:互联网 发布:网络用语你妹什么意思 编辑:程序博客网 时间:2024/05/21 13:52
题目:
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.
题意:
你拥有股票在k天的价格,寻找一个买入和卖出的时间,使受益最大。当然买入时间肯定需要早于等于卖出时间。
思路:
使用动态规划,我是从后面一天往前推算,profit[i]代表的是从第i天到最后一天的最大收益,并且保存从第i天到最后一天的价格的最大值max_price,对于计算profit[i-1],如果price[i-1] > max_price,那么更新max_price。并且profit[i-1] = profit[i].否则profit[i-1] = max(profit[i], max_price - price[i-1])。
以上。
代码如下:
class Solution {public: int maxProfit(vector<int>& prices) { if(prices.size() == 0)return 0; int * profit = new int[prices.size()]; int max_price = prices[prices.size() - 1]; profit[prices.size() - 1] = 0; for(int i = prices.size() - 2; i >= 0; i--){ if(prices[i] > max_price) { max_price = prices[i]; profit[i] = profit[i + 1]; } else { profit[i] = max(profit[i + 1],max_price - prices[i]); } } return profit[0]; }};
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
- C++11中的std::function
- 单例模式
- 希望帮对了人
- [前端] marquee使用
- LeetCode-House Robber II-解题报告
- [leetcode] 121. Best Time to Buy and Sell Stock
- Struts标签实现分页(当前页码在中间显示)
- java实现文件上传并预览效果
- http://blog.sina.com.cn/s/blog_4e7859dd01009xds.html
- Oracle DUAL 表
- Codeforces 557C Arthur and Table 乱搞题
- GCD 深入理解(一)
- CSS控制之IE常见BUG及解决方案
- android 签名出错