-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0853-car-fleet.js
More file actions
41 lines (35 loc) · 1.15 KB
/
0853-car-fleet.js
File metadata and controls
41 lines (35 loc) · 1.15 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
/**
* Car Fleet
* Time Complexity: O(N log N)
* Space Complexity: O(N)
*/
var carFleet = function (target, position, speed) {
const totalCarNumber = position.length;
const initialCarRecords = [];
for (let carIterator = 0; carIterator < totalCarNumber; carIterator++) {
const currentCarPositionValue = position[carIterator];
const currentCarSpeedValue = speed[carIterator];
const timeToDestination =
(target - currentCarPositionValue) / currentCarSpeedValue;
initialCarRecords.push({
startingPosition: currentCarPositionValue,
estimatedTime: timeToDestination,
});
}
initialCarRecords.sort(
(carOne, carTwo) => carTwo.startingPosition - carOne.startingPosition,
);
let fleetCounterValue = 0;
let slowestTimeObserved = 0;
let recordIndex = 0;
while (recordIndex < totalCarNumber) {
const currentRecord = initialCarRecords[recordIndex];
const currentCarCalculatedTime = currentRecord.estimatedTime;
if (currentCarCalculatedTime > slowestTimeObserved) {
fleetCounterValue++;
slowestTimeObserved = currentCarCalculatedTime;
}
recordIndex++;
}
return fleetCounterValue;
};