Codility passing car

Here is my code that got 100% in C#

class Solution
{
    public int solution(int[] A)
    {
        int count = 0;
        int multiply = 0;
        foreach (int car in A)
        {
            if (car == 0)
            {
                multiply = multiply + 1;
            }
            if (multiply > 0)
            {
                if (car == 1)
                {
                    count = count + multiply;
                    if (count > 1000000000)
                    {
                        return -1;
                    }
                }
            }
        }
        return count;
    }
}

Most of the answers here just provided algorithms to solve the task but not answering author original question. "Why is there only 5 pairs of car and not 6 ?" That is because cars (2,1) never pass each other.

Here is quick visualization of problem. enter image description here


Time Complexity - O(n) Space Complexity - O(1) The logic I came up with goes like this.

  • Have 2 variables. Count and IncrementVal. Initialize both to zero.
  • Traverse through the array. Every time you find a 0, increment the IncrementVal.
  • Every time you find a 1, modify count by adding the incrementVal to count.
  • After the array traversal is completed, return back the count.

Note:: Example code provided below assumes static array and a predefined array size. You can make it dynamic using vectors.

#include <iostream>
using namespace std;

int getPass(int* A, int N)
{
    unsigned long count = 0;
    int incrementVal = 0;
    for(int i = 0; i < N; i++)
    {
        if(A[i]==0)
        {
            incrementVal++;
        }
        else if (A[i]==1)
        {
            count = count + incrementVal;
        }
        if(count > 1000000000) return -1;
    }
    return count;
}

int main()
{
   int A[]={0,1,0,1,1};
   int size = 5;
   int numPasses = getPass(A,size);
   cout << "Number of Passes: " << numPasses << endl;
}

Tags:

Java