LeetCode(121)Best Time to Buy and Sell Stock

来源:互联网 发布:正义不会缺席知乎 编辑:程序博客网 时间:2024/05/16 03:39

题目如下:
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天买入,第j天卖出,现在i和j都是未知的。
先把j固定下来,假设已经找到了j,那么i的的取值范围是[ 第0天 ~ 第j-1天 ],用small表示 [ 第0天 ~ 第j-1天 ] 中的最便宜买入价对应的日期,small可以通过遍历第0天到第j-1天的价格得到。所以,如果已知一个确定的卖出日期j,那么很容易能够求出来一个买入日期small,使得i=small,达到利润最大化。
但是其实卖出日期j不是固定的,j可以的取值范围是从第0天到最后1天中的任何一天,所以对卖出日期j遍历所有的日期,求出每个j对应的最大利润,然后在最大利润中选择最大的最大利润就是答案。


我的代码:

//32ms 过大集合class Solution {public:    int maxProfit(vector<int> &prices) {        if(prices.size()==0)            return 0;        int i=0;        int j=i+1;        int small_price=prices[i];        int profit=0;        while(i<prices.size()-1){            j=i+1;            if(prices[i]<small_price)                small_price=prices[i];            int tmp=prices[j]-small_price;            if(tmp>profit)                profit=tmp;            i++;        }        if(profit<0)            profit=0;        return profit;    }};


小结分析:

1. 本质上,这道题目的思路是two pointers的思路,固定一个pointer,然后在固定当前pointer的情况下,考虑另外一个Point能够取得的最优值。

2. 和two pointer思路类似的题目是 minimum window substring。虽然完全不是同一个领域的题目,但是表达的two pointer的思路一直。在minimum window substr中,先固定了end这个pointer的值,然后考虑在end固定的情况下,begin如何变动可以取得最优解。

3. stock问题有4个系列,分别在 1, 2, 3, 4。



0 0
原创粉丝点击