-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPassingCars.js
More file actions
45 lines (26 loc) · 736 Bytes
/
Copy pathPassingCars.js
File metadata and controls
45 lines (26 loc) · 736 Bytes
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
44
45
// 6. Passing Cars
// Problem:
// Count the number of passing cars. A 0 represents a car traveling east, and a 1 represents a car traveling west. Each 0 can pair with all subsequent 1s.
// Example:
// Input: [0, 1, 0, 1, 1]
// Output: 5
// Solution Idea:
// Use a counter to track the number of east-bound cars and calculate passing pairs.
// Time Complexity: O(n).
// javascript
// Copy code
function passingPairs(A){
let eastCars = 0;
let passingPairs = 0;
for(const car of A){
if(car === 0){
eastCars++;
}else{
passingPairs+=eastCars
if(passingPairs > 1000000000000){
return -1
}
}
}
return passingPairs;
}