#2008

Maximum Earnings From Taxi

Medium
ArrayHash TableBinary SearchDynamic ProgrammingSortingDynamic ProgrammingSorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal solution uses dynamic programming to keep track of the maximum earnings at each point. By sorting the rides based on their end points, we can efficiently determine the best rides to take without overlap.

⚙️

Algorithm

5 steps
  1. 1Step 1: Sort the rides based on their end points.
  2. 2Step 2: Initialize a DP array where dp[i] represents the maximum earnings up to the i-th ride.
  3. 3Step 3: For each ride, calculate the profit and find the last non-overlapping ride using binary search.
  4. 4Step 4: Update the DP array with the maximum of taking the current ride or not.
  5. 5Step 5: Return the maximum value in the DP array.
solution.py11 lines
1def maxEarnings(n, rides):
2    rides.sort(key=lambda x: x[1])
3    dp = [0] * (len(rides) + 1)
4    for i in range(1, len(rides) + 1):
5        start_i, end_i, tip_i = rides[i - 1]
6        profit = (end_i - start_i + 1) + tip_i
7        j = 0
8        while j < i - 1 and rides[j][1] < start_i:
9            j += 1
10        dp[i] = max(dp[i - 1], profit + dp[j])
11    return dp[len(rides)]

Complexity note: The sorting step takes O(n log n), and filling the DP array takes O(n), leading to an overall complexity of O(n log n).

  • 1Sorting the rides by their end points allows for efficient selection of non-overlapping rides.
  • 2Dynamic programming helps in building up the maximum earnings incrementally.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.