Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 188 · State Machine / Stocks

Best Time to Buy and Sell Stock IV

LeetCode 188 · ಕಠಿಣ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

min_buy[i] = min(min_buy[i], price − max_profit[i-1]); max_profit[i] = max(max_profit[i], price − min_buy[i]).

ಕಠಿಣArrayDynamic Programming

ನಾನು Best Time to Buy and Sell Stock IV (LeetCode 188) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — State Machine / Stocks ಪ್ಯಾಟರ್ನ್‌ನ ಒಂದು ಕಠಿಣ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.

ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್‌ನಲ್ಲಿದೆ.

Intuition

Generalise the two-transaction chain to k. Transaction i's effective buy price is the stock price minus the profit already locked in by transaction i-1, so keep an array of k effective buys and k best profits and update them all on every day.

Approach

  1. 1

    Arrays of size k+1; index 0 is the 'no transaction yet' sentinel with profit 0.

  2. 2

    For each price, for i = 1..k: update the effective buy for trade i, then its best profit.

  3. 3

    max_profit[k] holds the best total using at most k trades.

ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ

k-state machinePythonO(n·k) time · O(k) space
class Solution:
    def maxProfit(self, k: int, prices: List[int]) -> int:
        min_buy = [float("inf")]*(k+1)
        max_profit = [0]*(k+1)
        for price in prices:
            for i in range(1,k+1):
                min_buy[i]=min(min_buy[i],price-max_profit[i-1])
                max_profit[i]=max(max_profit[i],price-min_buy[i])
        return max_profit[k]
ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

Best Time to Buy and Sell Stock IV — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು

Best Time to Buy and Sell Stock IV ಹಿಂದಿನ intuition ಏನು?

Generalise the two-transaction chain to k. Transaction i's effective buy price is the stock price minus the profit already locked in by transaction i-1, so keep an array of k effective buys and k best profits and update them all on every day.

Best Time to Buy and Sell Stock IV (LeetCode 188) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?

1. Arrays of size k+1; index 0 is the 'no transaction yet' sentinel with profit 0. 2. For each price, for i = 1..k: update the effective buy for trade i, then its best profit. 3. max_profit[k] holds the best total using at most k trades.

Best Time to Buy and Sell Stock IV ನ time ಮತ್ತು space complexity ಎಷ್ಟು?

Time: O(n · k). Space: O(k). (Accepted approach: k-state machine.)

Best Time to Buy and Sell Stock IV ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?

Note the argument order: k comes before prices. When k ≥ n/2 the problem becomes unlimited trades — the same code still works, just slower.