Python coding

Most pay from gigs that don't clash

Each gig is a triple [start, end, pay] of integers with start < end and pay > 0. You may take any set of gigs as long as no two of them overlap in time; a gig that starts exactly when another ends does not clash with it. Return the largest total pay you can earn.

The list is not sorted and may be empty (then the answer is 0). It can be long: trying every subset, or comparing every pair of gigs, is too slow. Aim for O(n log n).

Besides the tests, one large input (4,500 gigs) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • max_pay([[1,3,50],[2,4,10],[3,5,40],[3,6,70]]) → 120
  • max_pay([[1,2,5],[1,10,100],[2,3,5],[3,4,5]]) → 100
  • max_pay([[1,2,5],[2,3,5],[3,4,5]]) → 15
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Picking by earliest end, which maximizes how many gigs you take, fails here: one long gig can pay more than three short ones. Still sort by end, and decide gigs in that order.

Hint 2

Let best[i] be the most pay from the first i gigs sorted by end. Gig i is either skipped, giving best[i], or taken on top of the best total of the gigs that end by its start.

Hint 3

Ends are sorted, so the gigs that end by start form a prefix. Find its length with bisect_right(ends, start) instead of scanning back over every earlier gig.

Solution and why it works
pythonO(n log n) · O(n)
from bisect import bisect_right


def max_pay(gigs: list[list[int]]) -> int:
    gigs = sorted(gigs, key=lambda g: g[1])          # sweep in order of end time
    ends = [end for _, end, _ in gigs]
    best = [0] * (len(gigs) + 1)                     # best[i]: most pay from the first i gigs
    for i, (start, end, pay) in enumerate(gigs):
        j = bisect_right(ends, start, 0, i)          # gigs that end by this one's start
        best[i + 1] = max(best[i], best[j] + pay)    # skip it, or take it after those
    return best[-1]

Sorting by end makes each decision local: when you reach a gig, the gigs that fit before it (ending by its start) form a prefix, found by binary search, and its best total is already known. So the best either skips the gig or adds its pay to that prefix's best. The trap is the unweighted greedy, earliest end first: one well-paid long gig can beat several short ones. Scanning back for compatible gigs is correct but O(n²).