Passing Cars
100% | 100%
by sweetcoco
HTML
<h1>Passing Cars</h1>
<div id="brinza-task-description">
<p>A non-empty zero-indexed array A consisting of N integers is given. The consecutive elements of array A represent consecutive cars on a road.</p>
<p>Array A contains only 0s and/or 1s:</p>
<blockquote><ul style="margin: 10px;padding: 0px;"><li>0 represents a car traveling east,</li>
<li>1 represents a car traveling west.</li>
</ul>
</blockquote><p>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.</p>
<p>For example, consider array A such that:</p>
<p></p><pre><tt> A[0] = 0
A[1] = 1
A[2] = 0
A[3] = 1
A[4] = 1</tt></pre>
<p>We have five pairs of passing cars: (0, 1), (0, 3), (0, 4), (2, 3), (2, 4).</p>
<p>Write a function:</p>
<blockquote><p class="lang-c" style="font-family: monospace; font-size: 9pt; display: none"><tt>
int solution(int A[], int N);
</tt></p></blockquote>
<blockquote><p class="lang-cpp" style="font-family: monospace; font-size: 9pt; display: none"><tt>
int solution(vector<int> &A);
</tt></p></blockquote>
<blockquote><p class="lang-pas" style="font-family: monospace; font-size: 9pt; display: none"><tt>
function solution(A: array of longint; N: longint): longint;
</tt></p></blockquote>
<blockquote><p class="lang-java" style="font-family: monospace; font-size: 9pt; display: none"><tt>
class Solution { public int solution(int[] A); }
</tt></p></blockquote>
<blockquote><p class="lang-py" style="font-family: monospace; font-size: 9pt; display: none"><tt>
def solution(A)
</tt></p></blockquote>
<blockquote><p class="lang-php" style="font-family: monospace; font-size: 9pt; display: none"><tt>
function solution($A);
</tt></p></blockquote>
<blockquote><p class="lang-cs" style="font-family: monospace; font-size: 9pt; display: none"><tt>
class Solution { public int solution(int[] A); }
</tt></p></blockquote>
<blockquote><p class="lang-js" style="font-family:...
JavaScript
A = [0, 1, 0, 1, 1];
function solution(A) {
// write your code in JavaScript (Node.js 0.12)
var pairs = 0,
carsGoingEastCount = 0;
for (i = 0; i < A.length; i++) {
if(A[i] === 0) {
carsGoingEastCount ++;
}else {
pairs += carsGoingEastCount;
if (pairs > 1000000000) {
return -1;
}
}
}
return pairs;
}
console.log(solution(A));