- 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
- 52 lines of Python from the credited upstream file maximum-subarray-sum-after-at-most-k-swaps.py.
- The implementation visibly relies on sequence storage, work queue, 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 4import heapq5 6 78class Solution(object):9 def maxSum(self, nums, k):10 """11 :type nums: List[int]12 :type k: int13 :rtype: int14 """15 def update(heap, total, x):16 if k == 0:17 return total18 heapq.heappush(heap, x)19 total += x20 if len(heap) == k+1:21 total -= heapq.heappop(heap)22 return total23 24 cnt = sum(x < 0 for x in nums)25 if cnt == len(nums):26 return max(nums)27 if cnt <= k: 28 return sum(x for x in nums if x >= 0)29 prefix = [0]*(len(nums)+1)30 for i in xrange(len(nums)):31 prefix[i+1] = prefix[i]+nums[i]32 result = 033 dp = [0]*len(nums)34 for i in xrange(len(nums)):35 max_heap = [] 36 total1 = 037 for j in xrange(i, len(nums)):38 if nums[j] < 0:39 total1 = update(max_heap, total1, -nums[j])40 dp[j] = -total141 min_heap = []42 total2 = 043 for j in xrange(i):44 if nums[j] >= 0:45 total2 = update(min_heap, total2, nums[j])46 for j in reversed(xrange(i, len(nums))):47 result = max(result, (prefix[j+1]-prefix[i])-dp[j]+total2)48 if nums[j] >= 0:49 total2 = update(min_heap, total2, nums[j])50 result = max(result, total2)51 return result52