KatInterview

Maximum Earnings from Back-to-Back Booking Slots

Dynamic ProgrammingAuto-graded · 18 test cases
MediumAuto-gradedDynamic Programmingdynamic-programmingbinary-searchintervals

Last updated

Pick non-overlapping time slots, where one may begin exactly as another finishes, to maximize total payout; tests weighted interval scheduling with sorting, DP and binary search.

You manage a single resource, such as a meeting room, that can serve only one booking at a time. You are given a list of booking requests. Each request has a start time, a finish time and a payout. You may accept any subset of requests, as long as no two accepted bookings overlap in time. Return the largest total payout you can collect.

Input

  • bookings: a list where each element is [start, finish, payout], with three integers.

The booking i occupies the resource from start until finish.

Overlap rule

Two accepted bookings conflict only if their time ranges share some positive length of time. If one booking finishes at time t and another starts at exactly time t, they do not conflict, and both may be accepted.

You may accept any number of bookings, including just one. Each booking can be accepted at most once. If the list contains identical entries, they count as separate bookings, but any two of them overlap, so at most one of them can be accepted.

Output

Return a single integer: the maximum total payout over all valid selections.

Constraints

  • 1 <= len(bookings) <= 5 * 10^4
  • 1 <= start < finish <= 10^9 for every booking
  • 1 <= payout <= 10^4 for every booking
  • The answer is therefore at most 5 * 10^8.
  • The input list should not need to be modified.

Examples

Example 1

Input: max_booking_payout([[1, 4, 20], [2, 6, 30], [4, 7, 25], [7, 9, 15]])

Output: 60

Example 2

Input: max_booking_payout([[1, 2, 5], [1, 3, 6], [2, 3, 4]])

Output: 9

Example 3

Input: max_booking_payout([[1, 10, 100], [2, 3, 30], [3, 4, 30], [4, 5, 30]])

Output: 100

Hints

Hint 1

Simple greedy rules such as 'earliest finish first' or 'largest payout first' fail when payouts differ. Think about a decision for each booking: take it or skip it.

Hint 2

Sort the bookings by finish time. Let best[i] be the best payout using only the first i bookings in that order. When you take booking k, every other chosen booking must finish at or before its start.

Hint 3

In finish-time order, the bookings compatible with booking k that come before it form a prefix. Find the prefix length with binary search over the finish times, using a search that counts finish times less than or equal to the start. Then best[k+1] = max(best[k], best[prefix] + payout).