Given a non-empty null-indexed array A, consisting of N integers. The sequential elements of array A are sequential cars on the road.
Array A contains only 0s and / or 1s:
0 is a car traveling east, 1 is 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, passes when P moves east and Q travels west.
For example, consider an array A such that:
A [0] = 0 A [1] = 1 A [2] = 0 A [3] = 1 A [4] = 1 We have five pairs of passing cars: (0, 1), (0, 3), (0, 4), (2, 3), (2, 4).
Write a function:
class Solution {public int solution (int [] A); }
which, given the non-empty zero index A of N integers, returns the number of pairs of passing cars.
The function should return -1 if the number of pairs of passing cars exceeds 1,000,000,000.
For example, given:
A [0] = 0 A [1] = 1 A [2] = 0 A [3] = 1 A [4] = 1 the function should return 5, as explained above.
Let's pretend that:
N is an integer in the range [1.000000]; each element of array A is an integer that can have one of the following values: 0, 1. Complexity:
expected worst-case time complexity - O (N); expected worst-case space is O (1) complexity, outside of input storage (not counting storage required for input arguments). Elements of input arrays can be changed.
▶ medium_random random, length = ~ 10000 ✔ OK ▶ large_random random, = ~ 100 000 ✘ 1248768710 -1 ▶ large_big_answer 0..01..1, = ~ 100 000 ✘ -1794967296 -1 ▶ large_alternate 0101..01, = ~ 100 000 ✘ 1250025000 -1 ▶ _ 1s/0s, = ~ 100 000 ✔ OK