Passing Car East or West Codility Question
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.
For example, consider array A such that:
We have five pairs of passing cars: (0, 1), (0, 3), (0, 4), (2, 3), (2, 4).
The function should return 5, as explained above.
Assume that:
N is an integer within the range [1..100,000];
each element of array A is an integer that can have one of the following values: 0, 1.
The function should return −1 if the number of passing cars exceeds 1,000,000,000.
Read full article from Passing Car East or West Codility Question
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.
For example, consider array A such that:
1 | A[0] = 0 |
2 | A[1] = 1 |
3 | A[2] = 0 |
4 | A[3] = 1 |
5 | A[4] = 1 |
The function should return 5, as explained above.
Assume that:
N is an integer within the range [1..100,000];
each element of array A is an integer that can have one of the following values: 0, 1.
The function should return −1 if the number of passing cars exceeds 1,000,000,000.
int getPassingCars( int * A, int N) |
02 | { |
03 | unsigned long count = 0; |
04 | int totalOfZeros = 0; |
05 | for ( int i = 0; i < N; i++) |
06 | { |
07 | if (A[i]==0) |
08 | { |
09 | totalOfZeros ++; |
10 | } |
11 | else if (A[i]==1) |
12 | { |
13 | count = count + totalOfZeros; |
14 | } |
15 | if (count > 1000000000) return -1; |
16 | } |
17 | return count; |
18 | } |