121. Best Time to Buy and Sell Stock

problem description

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 (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:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 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
Explanation: In this case, no transaction is done, i.e. max profit = 0.

algorithm thought

只能买一次商品,一次交易。那么我们从第一天开始买商品,第一天必须买,因为只有一次机会。到了第二天的时候,如果第二天比第一天贵,我们就得到利润。如果第二天比第一天便宜,那我们就第二天再买。这里转化成代码的意思就是,我们遍历数组的过程,每次都记录最小值,当做我们购买的价格,每次都用当前值减去最小值,就是我们的利润。

code

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int res=0;
        int miprice=INT_MAX;
        for(auto price:prices){
            miprice=min(miprice,price);
            res=max(res,price-miprice);
        }
        return res;
    }
};

algorithm analysis

一次遍历就可以得到答案,时间复杂度O(n)

Last updated