LeetCode Question 122-The Best Time to Buy and Sell Stocks II-Python

topic

Given an array, its i-th element is the price of a given stock on the i-th day.

Design an algorithm to calculate the maximum profit you can get. You can complete as many transactions as possible (buying and selling a stock multiple times).

Note : You cannot participate in multiple transactions at the same time (you must sell the previous stock before buying again) .
Example :

输入: [7,1,5,3,6,4]
输出: 7
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 
      这笔交易所能获得利润 = 5-1 = 4 。
      随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 
      这笔交易所能获得利润 = 6-3 = 3 。
输入: [1,2,3,4,5]
输出: 4
解释: 在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 
      这笔交易所能获得利润 = 5-1 = 4 。
      注意你不能在第 1 天和第 2 天接连购买股票,之后再将它们卖出。
      因为这样属于同时参与了多笔交易,你必须在再次购买前出售掉之前的股票。
输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。

Tips :

1 <= prices.length <= 3 * 10 ^ 4
0 <= prices[i] <= 10 ^ 4

Official solution one: DP dynamic programming 1

The overall idea : write down the profit every day. Considering that there are only two statuses on the i day, holding stocks or not holding stocks, the status of holding stocks on that day may inherit stocks held on the previous day or stocks bought on the same day. In the same way, the status of not holding stocks on the day may inherit the status of not holding stocks on the previous day or selling stocks on the same day. Taking the last day not to hold stocks is the solution to the problem.
Explanation: The answer asks for the maximum profit on the last day, that is, the maximum profit on each previous day.

algorithm

Record the profit dp[i] on the i day, the profit on the i day dp[i][0] when the stock is not held, and the profit on the i day dp[i][1]
when the stock is held when dp[i][0 ] Is the transition state, that is, the state of not holding stocks on the i day, dp[i][0] comes from not holding stocks on the previous day-----dp[i-1][0]
or holding on the previous day Stock + dished out income on the day-----dp[i-1][1] + prices[i], whichever is the largest profit on the day

dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i])

Similarly, for the profit of holding stocks on day i, dp[i][1] comes from holding stocks on the previous day-----dp[i-1][1]
or not holding stocks on the previous day-that day Buying costs dp[i-1][0]-prices[i], whichever is the most profitable for the day

dp[i][1] = max(dp[i-1][1], dp[i-1][0] - prices[i])

The final answer can be understood as the profit after selling the stock on the last day: dp[n-1][0] (n is the total number of days)

Code

def maxProfit(prices) -> int:
        if not prices:
            return 0
        n = len(prices)
        dp = [[0]*2 for _ in range(n)]
        # dp[i][0]表示第i天不持有股票, dp[i][1]表示第i天持有股票
        dp[0][0], dp[0][1] = 0, - prices[0]
        for i in range(1, n):
            dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i])
            dp[i][1] = max(dp[i-1][1], dp[i-1][0] - prices[i])
        return dp[n-1][0]

Complexity analysis

Time complexity: O(n). Where n is the length of the array. There are a total of 2n states, and the time complexity of each state transition is O(1), so the time complexity is O(2n)=O(n).
Space complexity: O(n). We need to open up O(n)O(n) space to store all the states in the dynamic programming.

Official solution 2: Greedy

The overall idea : using greed in this question is more like a brain teaser. There are no restrictions on the number of transactions and handling fees. You can sell stocks every day, so add up the profit of each transaction greater than 0. Sell ​​as long as you earn more money today than yesterday.

Code

def maxProfit(prices) -> int:
        # 任意两天的收益等于连续每天买入卖出收益的总和,如果要得到最大值,
        # 那么需要连续每天交易时只取收益为正数的那天即可
        N = len(prices)
        res = 0
        for i in range(N-1):
            if prices[i] < prices[i+1]:
                res = prices[i+1] - prices[i] + res
        return res

Complex analysis

Time complexity: O(n). Where nn is the length of the array. We only need to traverse the array once.
Space complexity: O(1). Only need constant space to store several variables.

Refer to the comment section to send the big star star's comment 2


  1. https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/solution/mai-mai-gu-piao-de-zui-jia-shi-ji-ii-by-leetcode-s/ ↩︎

  2. https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/comments/ ↩︎

Guess you like

Origin blog.csdn.net/qq_42388742/article/details/109563278