3.9 the best time to buy and sell stocks

topic

Given an array, which i-th element is a given stock i-day prices.

If you are only allowed up to complete a transaction (ie buying and selling a stock), to design an algorithm to compute the maximum profit you can get.

Note that you can not sell the stock before buying stocks.

Example 1

输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
     注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。

Example 2

输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。

Thinking

  • Record the minimum value to the left, in the course traversed by calculating earnings update the maximum benefit, experiencing smaller than the minimum value of the number of updates the minimum value until the end.

Code

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if ( prices.size() < 2 ) return 0;

        int profit = ( prices[1] > prices[0] ? prices[1] - prices[0] : 0 );
        int minVal = min( prices[0], prices[1] );

        for ( int i = 2; i < prices.size(); ++i ) {
            if ( prices[i] > minVal )
                profit = max( profit, prices[i] - minVal );
            else 
                minVal = prices[i];
        }

        return profit;
    }
};
He published 183 original articles · won praise 43 · views 60000 +

Guess you like

Origin blog.csdn.net/m0_37822685/article/details/104769569