- 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
- 39 lines of Python from the credited upstream file 3414.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.
1from dataclasses import dataclass2 3 4@dataclass(frozen=True)5class T:6 weight: int7 selected: tuple[int]8 9 def __iter__(self):10 yield self.weight11 yield self.selected12 13 14class Solution:15 def maximumWeight(self, intervals: list[list[int]]) -> list[int]:16 intervals = sorted((*interval, i) for i, interval in enumerate(intervals))17 18 @functools.lru_cache(None)19 def dp(i: int, quota: int) -> T:20 """21 Returns the maximum weight and the selected intervals for intervals[i..n),22 where `quota` is the number of intervals that can be selected.23 """24 if i == len(intervals) or quota == 0:25 return T(0, ())26 27 skip = dp(i + 1, quota)28 29 _, r, weight, originalIndex = intervals[i]30 j = bisect.bisect_right(intervals, (r, math.inf))31 nextRes = dp(j, quota - 1)32 pick = T(weight + nextRes.weight,33 sorted((originalIndex, *nextRes.selected)))34 return (pick if (pick.weight > skip.weight or35 pick.weight == skip.weight and pick.selected < skip.selected)36 else skip)37 38 return list(dp(0, 4).selected)39