The best time to buy stocks

Leecode brush title

  • Title Description

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.

  • Examples

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Day 2 (= 1 stock price), when buying, on day 5 (stock price = 6), when sold, The maximum profit = 6-1 = 5.
Note that profits can not be 7-1 = 6, because the selling price must be greater than the purchase price.
Enter: [7,6,4,3,1]
Output: 0
to explain: In this case, no transaction is completed, the maximum profit is zero.

  • Code (dynamic programming)
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int min_price=INT_MAX;
        int profit=0;
        for(int i=0;i<prices.size();++i)
        {
            min_price=min(min_price,prices[i]);
            profit=max(profit,prices[i]-min_price);
        }
        return  profit;  
    }
};

Guess you like

Origin blog.csdn.net/qq_42780025/article/details/91345249