How does LeetCode solve the problem of the best time to buy and sell stocks
This article is about how LeetCode solves the problem of the best time to buy and sell stocks. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Given an array of prices, the I element prices [I] represents the price of a given stock on the first day. You can only choose to buy the stock one day and sell it at a different date in the future. Design an algorithm to calculate the maximum profit you can make. Return to the maximum profit you can make from the deal. If you can't make any profit, return 0. Output: 5 explanation: buy on day 2 (stock price = 1) and sell on day 5 (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; at the same time, you can't sell the stock before buying. Example 2: input: prices = [7 ~ 6 ~ 4 ~ 3 ~ 1] output: 0 explanation: in this case, no transaction is completed, so the maximum profit is 0. Tip: 1