- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 66 lines of Python from the credited upstream file best-time-to-buy-and-sell-stock-v.py.
- The implementation visibly relies on sequence storage, cached states.
- No explicit loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution(object):6 def maximumProfit(self, prices, k):7 """8 :type prices: List[int]9 :type k: int10 :rtype: int11 """12 dp = [0]*(len(prices)+1)13 result = 014 for i in xrange(k):15 x, y = float("-inf"), float("-inf")16 new_dp = [float("-inf")]*(len(prices)+1)17 for j in xrange(i, len(prices)):18 x, y = max(x, dp[j]-prices[j]), max(y, dp[j]+prices[j])19 new_dp[j+1] = max(new_dp[j], x+prices[j], y-prices[j])20 dp = new_dp21 result = max(result, dp[-1])22 return result23 24 25262728class Solution(object):29 def maximumProfit(self, prices, k):30 """31 :type prices: List[int]32 :type k: int33 :rtype: int34 """35 bought = [float("-inf")]*k36 sold = [float("-inf")]*k37 result = [0]*(k+1)38 for x in prices:39 for i in reversed(xrange(k)):40 result[i+1] = max(result[i+1], bought[i]+x, sold[i]-x)41 bought[i] = max(bought[i], result[i]-x)42 sold[i] = max(sold[i], result[i]+x)43 return result[-1]44 45 46474849class Solution3(object):50 def maximumProfit(self, prices, k):51 """52 :type prices: List[int]53 :type k: int54 :rtype: int55 """56 bought = [float("-inf")]*k57 sold = [float("-inf")]*k58 result = [float("-inf")]*(k+1)59 result[0] = 060 for x in prices:61 for i in reversed(xrange(k)):62 result[i+1] = max(result[i+1], bought[i]+x, sold[i]-x)63 bought[i] = max(bought[i], result[i]-x)64 sold[i] = max(sold[i], result[i]+x)65 return max(result)66