Funcia
Lv.3binary-searchdpsorting

Non-Overlapping Shows for Maximum Profit

Memory limit
256 MB
Correctness time limit
10000 ms
Solvers
0
0

You rent out one hall. shows[i] = [s, e, p] is a show that starts at time s, ends at time e (s < e) and pays p. Only one show can run at a time; a show may start exactly when the previous one ends (e ≤ s' means no overlap). Return the maximum total profit of a set of pairwise non-overlapping shows.

Examples

showsresult
[[1, 3, 50], [3, 5, 20], [2, 6, 100], [6, 7, 10]]110
[[0, 10, 5], [0, 5, 3], [5, 10, 3]]6
[[1, 2, 7]]7

Example 1 — [2, 6) (100) plus [6, 7) (10).

Efficiency

This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.

Function signature

solution(shows: int[][]) → long

Constraints

  • 1≤N=1 \le N = shows.length ≤200,000\le 200{,}000
  • 0≤0 \le s << e ≤109\le 10^9, 1≤1 \le p ≤106\le 10^6
  • The answer may exceed 32 bits.

Expected complexity

Time
O(N log N)
Space
O(N)

Examples

showsExpected
[[1,3,50],[3,5,20],[2,6,100],[6,7,10]]110
[[0,10,5],[0,5,3],[5,10,3]]6
[[1,2,7]]7

Hint

Hint

Greedy by end time fails with profits. Sort by end time; best[i] = max(best[i-1], p_i + best[j]) where j is the number of shows ending at or before show i starts — found by binary search over the sorted end times. Scanning all earlier shows for every show is O(N2)O(N^2) and exceeds the time limit.

Time limits per language

LanguageEfficiency time limit
C (GCC, gnu17)270 msestimated
C++ (GCC, gnu++23)270 msderived
Python 3.131000 msderived
Java 252250 msderived
Kotlin 2.4 (JVM)1540 msestimated
C# 14 (.NET 10)1540 msestimated

Test groups

GroupWeightTestsVisibility
sample03inputs and outputs
correctness4011verdict only
performance604verdict only
Loading editor…
Log in to run or submit code.

No result yet. Run or submit your code.