Leetcode 121. The best time to buy and sell stocks [series topics]

Problem Description

Given an array, its i-th element is the price of the i-th day of a given stock.
If you are only allowed to complete a single transaction (that is, buy and sell a stock once), design an algorithm to calculate the maximum profit you can get.
Note: You cannot sell stocks before buying them.

Problem solving report

Iterate through the array in sequence, saving the minimum value in the traversed array.
If the current traversed element is greater than the minimum value, it is assumed that the current sell, the minimum value corresponding to the day of purchase, update the maximum profit that can be obtained.

Implementation code

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int ans=0,MINN=INT_MAX;
        for(int i=0;i<prices.size();i++){
            if(prices[i]<MINN) MINN=prices[i];
            else ans=max(ans,prices[i]-MINN);
        }
        return ans;
    }
};

References

[1] Leetcode 121. The best time to buy and sell stocks

MD_
Published 139 original articles · praised 8 · 10,000+ views

Guess you like

Origin blog.csdn.net/qq_27690765/article/details/105354316