The sword refers to Offer 63. The maximum profit of stocks (C++) dynamic programming

Assuming that the price of a certain stock is stored in an array in chronological order, what is the maximum profit that can be obtained from buying and selling the stock at one time?

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。

Restrictions:
0 <= array length <= 10^5

Note: This question is the same as the 121 question on the main website: https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/

Problem-solving ideas:

Reference: https://blog.csdn.net/qq_30457077/article/details/113883623

class Solution {
    
    
public:
    int maxProfit(vector<int>& prices) {
    
    
        int inf = 1e9;//1e9 为1 000 000 000
        int minprice = inf, maxprofit = 0;
        for (int price: prices) {
    
    
            maxprofit = max(maxprofit, price - minprice);
            //第一轮的maxprofit为0,第二轮:若prices[1]<prices[0],
            //则maxprofit为prices[1]-prices[0]
            minprice = min(price, minprice);
            //第一轮的minprofit为prices[0]
        }
        return maxprofit;
    }
};

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_30457077/article/details/114982324