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