-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path11 PassingCars
32 lines (25 loc) · 1.04 KB
/
11 PassingCars
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
/*------------------------------------------------------------------------------
A non-empty array A consisting of N integers is given.
The consecutive elements of array A represent consecutive cars on a road.
Array A contains only 0s and/or 1s:
-- 0 represents a car traveling east,
-- 1 represents a car traveling west.
The goal is to count passing cars.
We say that a pair of cars (P, Q), where 0 ≤ P < Q < N,
is passing when P is traveling to the east and Q is traveling to the west.
The function should return −1 if the number of pairs of passing cars exceeds 1,000,000,000.
------------------------------------------------------------------------------*/
function solution(A) {
// write your code in JavaScript (Node.js 8.9.4)
let east = 0;
let maxPassingCars = 1000000000;
let passingCars = 0;
A.forEach(function (car) {
if (car === 0) east += 1
if (car === 1) {
passingCars += east;
if (passingCars > maxPassingCars) return -1;
}
});
return passingCars;
}