121. Best Time to Buy and Sell Stock--easy

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.

1.思考

  • 相当于找出上升的差值最大的两个点,即先出现较小值,再出现较大值;
  • 先从左往右找出到当前值为止的最小值,存放在lmin中;
  • 再从右往左找出到当前值为止的最大值,存放在rmax中;
  • 然后相应位置相减,求出差值最大的值。
    eg.
    prices : 7 1 5 3 6 4
    lmin : 7 1 1 1 1 1
    rmax : 7 6 6 6 6 6
    diff : 0 5 5 5 5 5

2.实现
Runtime: 4ms (100%)

class Solution {
public:
    // The key of this problem is to find 
    // the minimum of the leftarray and the maximum of the rightarray.
    int maxProfit(vector<int>& prices) {
        int len=prices.size(), i=0, j=0;
        vector<int> lmin(len), rmax(len);
        int result = 0;
        
        if(len<2)
            return result;
        
        lmin[0] = prices[0];
        rmax[len-1] = prices[len-1];
        for(i=1; i<len; i++){
            lmin[i] = min(lmin[i-1], prices[i]);
            rmax[len-1-i] = max(rmax[len-i], prices[len-1-i]);
        }
        
        for(i=0; i<len; i++){
            if(lmin[i] < rmax[i])     
                result = max(rmax[i]-lmin[i], result);
        }
        
        return result;
    }
};
原文地址:https://www.cnblogs.com/xuyy-isee/p/10600944.html