There is a car with capacity empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).
You are given the integer capacity and an array trips where trips[i] = [numPassengersi, fromi, toi] indicates that the ith trip has numPassengersi passengers and the locations to pick them up and drop them off are fromi and toi respectively. The locations are given as the number of kilometers due east from the car's initial location.
Return true if it is possible to pick up and drop off all passengers for all the given trips, or false otherwise.
Example 1:
Input: trips = [[2,1,5],[3,3,7]], capacity = 4 Output: false
Example 2:
Input: trips = [[2,1,5],[3,3,7]], capacity = 5 Output: true
Constraints:
1 <= trips.length <= 1000trips[i].length == 31 <= numPassengersi <= 1000 <= fromi < toi <= 10001 <= capacity <= 105
class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
delta = [0] * 1001
for num, start, end in trips:
delta[start] += num
delta[end] -= num
return all(s <= capacity for s in accumulate(delta))class Solution {
public boolean carPooling(int[][] trips, int capacity) {
int[] delta = new int[1001];
for (int[] trip : trips) {
int num = trip[0], start = trip[1], end = trip[2];
delta[start] += num;
delta[end] -= num;
}
int cur = 0;
for (int num : delta) {
cur += num;
if (cur > capacity) {
return false;
}
}
return true;
}
}/**
* @param {number[][]} trips
* @param {number} capacity
* @return {boolean}
*/
var carPooling = function (trips, capacity) {
let delta = new Array(1001).fill(0);
for (let [num, start, end] of trips) {
delta[start] += num;
delta[end] -= num;
}
let s = 0;
for (let num of delta) {
s += num;
if (s > capacity) {
return false;
}
}
return true;
};class Solution {
public:
bool carPooling(vector<vector<int>>& trips, int capacity) {
vector<int> delta(1001);
for (auto& trip : trips) {
int num = trip[0], start = trip[1], end = trip[2];
delta[start] += num;
delta[end] -= num;
}
int cur = 0;
for (auto& num : delta) {
cur += num;
if (cur > capacity) {
return false;
}
}
return true;
}
};func carPooling(trips [][]int, capacity int) bool {
delta := make([]int, 1010)
for _, trip := range trips {
num, start, end := trip[0], trip[1], trip[2]
delta[start] += num
delta[end] -= num
}
cur := 0
for _, num := range delta {
cur += num
if cur > capacity {
return false
}
}
return true
}