- 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
- 53 lines of Python from the credited upstream file subsequence-sum-after-capping-elements.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 subsequenceSumAfterCapping(self, nums, k):7 """8 :type nums: List[int]9 :type k: int10 :rtype: List[bool]11 """12 result = [False]*len(nums)13 nums.sort()14 mask = (1<<(k+1))-115 dp = 116 i = 017 for x in xrange(1, len(nums)+1):18 while i < len(nums) and nums[i] < x:19 dp |= (dp<<nums[i])&mask20 i += 121 for j in xrange(max(k%x, k-(len(nums)-i)*x), k+1, x):22 if dp&(1<<j):23 result[x-1] = True24 break25 return result26 27 28293031class Solution2(object):32 def subsequenceSumAfterCapping(self, nums, k):33 """34 :type nums: List[int]35 :type k: int36 :rtype: List[bool]37 """38 result = [False]*len(nums)39 nums.sort()40 dp = [False]*(k+1)41 dp[0] = True42 i = 043 for x in xrange(1, len(nums)+1):44 while i < len(nums) and nums[i] < x:45 for j in reversed(xrange(nums[i], k+1)):46 dp[j] = dp[j] or dp[j-nums[i]]47 i += 148 for j in xrange(max(k%x, k-(len(nums)-i)*x), k+1, x):49 if dp[j]:50 result[x-1] = True51 break52 return result53