[Leetcode Daily Notes] 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 stocks before buying again).

Example 1:

Input: [7,1,5,3,6,4] Output: 7 Explanation: Buy on the 2nd day (stock price = 1), and
sell on the 3rd day (stock price = 5). This exchange can make a profit = 5-1 = 4.
Then, buy on the 4th day (stock price = 3), and sell on the 5th day (stock price = 6). This exchange can make a profit = 6-3 = 3.

Example 2:

Input: [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (stock price =
1), sell on day 5 (stock price = 5), this The exchange can make a profit = 5-1 = 4.
Note that you cannot buy stocks one after another on the first day and the second day, and then sell them later.
Because this is involved in multiple transactions at the same time, you must sell the previous stocks before buying again.

Example 3:

Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is completed, so the maximum profit is 0.

prompt:

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

Problem-solving ideas

Dynamic programming

In the state definition
dp[i][j], i represents the money held on the i-th day (starting from 0); j has two states: 0 means no holdings on the day, 1 means holdings on the day; and every time When trading, you only need to deduct the handling fee once, that is, when buying or selling.
State transition equation

status Transfer process
Do not hold shares on the day Did not hold shares yesterday
Yesterday's holding + today's stock price
Shareholding on the day Yesterday's holding
Yesterday did not hold shares-today's share price

which isdp[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])

greedy

Be greedy at all times, sell when there is a high price, do not operate when there is a low price, trade as long as there is a profit, and only care about the profit.

Code

# 动态规划
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if not prices:
            return 0
        dp = [[0,-prices[0]]]
        for i in range(1,len(prices)):
            dp.append([max(dp[i-1][0],dp[i-1][1]+prices[i]),max(dp[i-1][1],dp[i-1][0]-prices[i])])
        return dp[-1][0]
# 贪心
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        sum=0
        for i in range(len(prices)-1):
            if prices[i+1]-prices[i]>0:
                sum+=prices[i+1]-prices[i]
        return sum

[Leetcode Daily Notes] 123. The Best Time to Buy and Sell Stocks III (Python)

Guess you like

Origin blog.csdn.net/qq_36477513/article/details/111313918