Leetcode - Best Time to Buy and Sell Stock
来源:互联网 发布:淘宝修改我的评价 编辑:程序博客网 时间:2024/06/10 21:58
Question
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.
Java Code
public int maxProfit2(int[] prices) { int len = prices.length; if(len < 2) return 0; int max = 0; int buy = prices[0]; int[] maxEarning = new int[len]; maxEarning[0] = 0; for(int i = 1; i < len; ++i) { //计算当前天卖出股票的收益,并比较得到全局的最大收益max if((maxEarning[i] = prices[i] - buy) > max) max = maxEarning[i]; //更新股票的历史最低报价,作为买入的价格buy if(prices[i] < buy) buy = prices[i]; } return max;}
说明
- 本题看似是一个很简单的问题,本质上就是求价格曲线的极大值与极小值之差,且要求极大值必须出现在极小值之后,即股票以最低价买入最高价卖出所得的收益才是最大,但是这里股票价格是一系列离散的点,无法用连续函数的导数求出极值,只能逐个点进行比较。如果使用动态规划的思想来解决这个问题就显得比较容易了,其状态转移关系是,当前天的收益等于当天的股票报价减去历史最低报价,所以只需要一直更新历史最低报价就行,则股票的全局最大收益就是所有天收益中的最大值。
0 0
- 【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
- C++访问Oracle数据库
- 【模板】LCA
- ed2k 中的信誉和分段机制代码梳理
- 【模板】dinic
- hdoj1007
- Leetcode - Best Time to Buy and Sell Stock
- 【模板】AC自动机
- C++使用oracle的occi库操作oracle数据库
- Android滚轮时间选择控件(可扩展自定义)
- PullDownRefreshLayout 自定义Android下拉刷新。
- eMule中的kad相关代码梳理
- R语言编码规范(Google)
- BNUOJ-50393-Carries
- android学习记录 Onclick事件监听