-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path2008-maximum-earnings-from-taxi.js
More file actions
43 lines (40 loc) · 1.5 KB
/
2008-maximum-earnings-from-taxi.js
File metadata and controls
43 lines (40 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* 2008. Maximum Earnings From Taxi
* https://leetcode.com/problems/maximum-earnings-from-taxi/
* Difficulty: Medium
*
* There are n points on a road you are driving your taxi on. The n points on the road are
* labeled from 1 to n in the direction you are going, and you want to drive from point 1
* to point n to make money by picking up passengers. You cannot change the direction of the taxi.
*
* The passengers are represented by a 0-indexed 2D integer array rides, where
* rides[i] = [starti, endi, tipi] denotes the ith passenger requesting a ride from point
* starti to point endi who is willing to give a tipi dollar tip.
*
* For each passenger i you pick up, you earn endi - starti + tipi dollars. You may only drive
* at most one passenger at a time.
*
* Given n and rides, return the maximum number of dollars you can earn by picking up the
* passengers optimally.
*
* Note: You may drop off a passenger and pick up a different passenger at the same point.
*/
/**
* @param {number} n
* @param {number[][]} rides
* @return {number}
*/
var maxTaxiEarnings = function(n, rides) {
rides.sort((a, b) => a[1] - b[1]);
const dp = new Array(n + 1).fill(0);
let rideIndex = 0;
for (let point = 1; point <= n; point++) {
dp[point] = dp[point - 1];
while (rideIndex < rides.length && rides[rideIndex][1] === point) {
const [start, end, tip] = rides[rideIndex];
dp[point] = Math.max(dp[point], dp[start] + (end - start + tip));
rideIndex++;
}
}
return dp[n];
};