Clever solution: the best time to buy and sell stocks

Problem:
Given an array, its i-th element is the price of a given stock on the i-th day.
If you are only allowed to complete at most one transaction (that is, buy and sell one stock), design an algorithm to calculate the maximum profit you can make.
Note that you cannot sell stocks before buying them.
Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on the 2nd day (stock price = 1), and sell on the 5th day (stock price = 6). Maximum profit = 6-1 = 5.
Note that the profit cannot be 7-1 = 6, because the selling price needs to be greater than the buying price.

Example 2:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is completed, so the maximum profit is 0.

 Solution: traverse once

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int inf = 1e9;//1e9 表示一个大数,记为无穷大
        int minprice = inf; 
        int maxprofit = 0;

        for (int price: prices) {
            //每次取最大利润
            maxprofit = max(maxprofit, price - minprice);
            //每次计算最小的买入价格
            minprice = min(price, minprice);
        }
        return maxprofit;
    }
};

Iterate through each number and record the smallest price. In the process of traversal, each time the current value minus the recorded minimum value is compared with the last maximum profit, the larger profit is selected. The maximum profit can be obtained by traversing the array.

Time complexity: O(n)O(n), only need to traverse once.
Space complexity: O(1)O(1), only constant variables are used

 

Reference address: https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/solution/121-mai-mai-gu-piao-de-zui-jia-shi-ji -by-leetcode-/

Guess you like

Origin blog.csdn.net/ma2595162349/article/details/109048967