|
| 1 | +""" |
| 2 | +Author : Abhiraj Mandal |
| 3 | +Date : October 3, 2025 |
| 4 | +
|
| 5 | +Weighted Interval Scheduling (Dynamic Programming) implementation in Python. |
| 6 | +
|
| 7 | +Problem: |
| 8 | +Given a set of intervals with start time, end time, and weight, |
| 9 | +find a subset of non-overlapping intervals with the maximum total weight. |
| 10 | +""" |
| 11 | + |
| 12 | +from __future__ import annotations |
| 13 | + |
| 14 | +from typing import NamedTuple |
| 15 | + |
| 16 | + |
| 17 | +class Interval(NamedTuple): |
| 18 | + start: int |
| 19 | + end: int |
| 20 | + weight: int |
| 21 | + |
| 22 | + |
| 23 | +def weighted_interval_scheduling(intervals: list[Interval]) -> int: |
| 24 | + """ |
| 25 | + Compute the maximum total weight of non-overlapping intervals. |
| 26 | +
|
| 27 | + >>> intervals = [Interval(1, 3, 5), Interval(2, 5, 6), Interval(4, 6, 5)] |
| 28 | + >>> weighted_interval_scheduling(intervals) |
| 29 | + 10 |
| 30 | + """ |
| 31 | + if not intervals: |
| 32 | + return 0 |
| 33 | + |
| 34 | + intervals.sort(key=lambda x: x.end) |
| 35 | + |
| 36 | + p = [0] * len(intervals) |
| 37 | + for j in range(len(intervals)): |
| 38 | + p[j] = -1 |
| 39 | + for i in range(j - 1, -1, -1): |
| 40 | + if intervals[i].end <= intervals[j].start: |
| 41 | + p[j] = i |
| 42 | + break |
| 43 | + |
| 44 | + n = len(intervals) |
| 45 | + dp = [0] * n |
| 46 | + for j in range(n): |
| 47 | + incl = intervals[j].weight |
| 48 | + if p[j] != -1: |
| 49 | + incl += dp[p[j]] |
| 50 | + dp[j] = max(incl, dp[j - 1] if j > 0 else 0) |
| 51 | + |
| 52 | + return dp[-1] |
| 53 | + |
| 54 | + |
| 55 | +if __name__ == "__main__": |
| 56 | + import doctest |
| 57 | + |
| 58 | + doctest.testmod() |
| 59 | + print("All doctests passed!") |
| 60 | + |
| 61 | + # Manual test suite |
| 62 | + test_cases = [ |
| 63 | + ([Interval(1, 3, 5), Interval(2, 5, 6), Interval(4, 6, 5)], 10), |
| 64 | + ([Interval(1, 2, 50)], 50), |
| 65 | + ([Interval(1, 4, 5), Interval(2, 5, 6), Interval(3, 6, 5)], 6), |
| 66 | + ([Interval(1, 2, 10), Interval(3, 4, 20), Interval(5, 6, 30)], 60), |
| 67 | + ( |
| 68 | + [ |
| 69 | + Interval(1, 2, 50), |
| 70 | + Interval(3, 5, 20), |
| 71 | + Interval(6, 19, 100), |
| 72 | + Interval(2, 100, 200), |
| 73 | + ], |
| 74 | + 250, |
| 75 | + ), |
| 76 | + ] |
| 77 | + |
| 78 | + for idx, (intervals, expected) in enumerate(test_cases, 1): |
| 79 | + result = weighted_interval_scheduling(intervals) |
| 80 | + print(f"Testcase {idx}: Expected={expected}, Got={result}") |
| 81 | + assert result == expected, f"Testcase {idx} failed!" |
| 82 | + |
| 83 | + print("\nAll manual test cases successfully passed!") |
0 commit comments