121. Best Time to Buy and Sell Stock
Say you have an array for which the $i^{th}$ element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Note that you cannot sell a stock before you buy one.
Example 1:
1 | Input: [7,1,5,3,6,4] |
Example 2:
1 | Input: [7,6,4,3,1] |
题目要求为,选择最佳的买入卖出时间,得到最大收益。
暴力搜索
复杂度$O(n^2)$ 确切一点是 $O(\frac{n(n+1)}{2})$
one pass
对于$[7, 1, 5, 3, 6, 4] $
可以知道,我们感兴趣的是峰谷之间的差值。则我们只需要找到当前值与之前最小值的最大差值即可。
1 | public class Solution { |
本文标题:121. Best Time to Buy and Sell Stock
文章作者:王二
发布时间:2018-08-02
最后更新:2024-11-06
原始链接:https://wanger-sjtu.github.io/Best_Time_to_Buy_and_Sell_Stock%20/
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!