Approach
Breadth-first search
For Maximum Sum of M Non Overlapping Subarrays II, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 76 lines of Python from the credited upstream file maximum-sum-of-m-non-overlapping-subarrays-ii.py.
- The implementation visibly relies on sequence storage, work queue, cached states.
- No explicit loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4import collections5 6 78class Solution(object):9 def maximumSum(self, nums, m, l, r):10 """11 :type nums: List[int]12 :type m: int13 :type l: int14 :type r: int15 :rtype: int16 """17 NEG_INF = float("-inf")18 def binary_search(left, right, check):19 while left <= right:20 mid = left+(right-left)221 if check(mid):22 right = mid-123 else:24 left = mid+125 return left26 27 def best_single():28 result = NEG_INF29 dq = collections.deque()30 for i in xrange(1, len(nums)+1):31 j = i-l32 if j >= 0:33 while dq and prefix[dq[-1]] >= prefix[j]:34 dq.pop()35 dq.append(j)36 while dq and dq[0] < i-r:37 dq.popleft()38 if dq:39 result = max(result, prefix[i]-prefix[dq[0]])40 return result41 42 def f(x):43 def better(v1, c1, v2, c2):44 return v1 > v2 or (v1 == v2 and c1 < c2)45 46 dp = [[0]*2 for _ in xrange(len(nums)+1)]47 dq = collections.deque()48 for i in xrange(1, len(nums)+1):49 j = i-l50 if j >= 0:51 while dq and better(dp[j][0]-prefix[j], dp[j][1], dp[dq[-1]][0]-prefix[dq[-1]], dp[dq[-1]][1]):52 dq.pop()53 dq.append(j)54 while dq and dq[0] < i-r:55 dq.popleft()56 dp[i] = dp[i-1]57 if dq:58 new_dp = [((dp[dq[0]][0]-prefix[dq[0]])+prefix[i])-x, dp[dq[0]][1]+1]59 if better(new_dp[0], new_dp[1], dp[i][0], dp[i][1]):60 dp[i] = new_dp61 return dp[-1]62 63 prefix = [0]*(len(nums)+1)64 for i in xrange(len(nums)):65 prefix[i+1] = prefix[i]+nums[i]66 single = best_single()67 dp, cnt = f(0)68 if not cnt:69 return single70 if cnt <= m:71 return dp72 mx = single73 assert(f(mx)[1] <= m)74 x = binary_search(1, mx, lambda x: f(x)[1] <= m)75 return f(x)[0]+m*x76