Leetcode 121 Best time to buy and sell stocks

Title description :
Given an array prices, its i-th element prices[i] represents the price of a given stock on the i-th day.

You can only choose to buy the stock on one day and sell it on a different day in the future. Design an algorithm to calculate the maximum profit you can make.

Returns the maximum profit you can make from this trade. If you can't make any profit, return 0.

Example :
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (stock price = 1), sell on day 5 (stock price = 6) Out, the 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 cannot sell the stock before buying.

Solution 1 :
Traverse the array once and calculate the minimum stock price and maximum profit each time until the day. Because the maximum profit must be to buy at the lowest point and sell at the highest point.
Time complexity: O(n), traversing the array once.
Space complexity: O(1), using limited variables.

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        max_profit = 0
        min_price = float("inf")
        for i in prices:
            if i<min_price:
                min_price = i
            cur_profit = i - min_price
            if cur_profit>max_profit:
                max_profit = cur_profit
        return max_profit

Solution 2 : Dynamic programming , the method of the stock problem is ""dynamic programming", because it contains overlapping sub-problems, that is, the best time to buy and sell stocks is determined by the state of buying or not buying before, and buying or not buying before It is determined by the earlier state. Here dp[i] represents the maximum profit of the previous i day
Insert image description here

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        n = len(prices)
        if n== 0 : return 0
        dp = [0]*n
        min_price =prices[0]
        for i in range(1,n):
            min_price = min(min_price,prices[i])
            dp[i] = max(dp[i-1],prices[i]-min_price)
        return dp[-1]

Complexity analysis
Time complexity: O(n).
Space complexity: O(n).

Refer : stock question (Python3, C++)

Guess you like

Origin blog.csdn.net/Rolandxxx/article/details/128564174