Medium
LABMaximum Earnings From Taxi
Given rides [start,end,tip], return the maximum earnings from non-overlapping rides.
EXAMPLES
Example 1
Input
{
"n": 5,
"rides": [
[
2,
5,
4
],
[
1,
5,
1
]
]
}
Output
7FUNCTION SHAPE
n: intrides: intMatrix→intSOLUTION NOTE
Identical structure to job scheduling. Sort rides, use binary search to find next available ride after current ends.
Reveal reference solution +
pythonREFERENCE
def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int:
rides.sort()
@cache
def dp(i):
if i >= len(rides): return 0
start, end, tip = rides[i]
earn = end - start + tip
next_idx = bisect_left(rides, (end,), key=lambda x: x[0])
return max(earn + dp(next_idx), dp(i + 1))
return dp(0)Time
O(n log n)Space
O(n)