Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How does LeetCode solve the problem of the best time to buy and sell stocks

Shulou Source: shulou.com Published: 2022-05-31 23:51:22 10月03日 Update

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

Tags: Maximum stock price profit complexity complexity time ideas methods problems returns numbers arrays time selection timing minimum code content variables Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple Shulou Technology Redmi Shulou Information Huawei