Count the number of passing cars on the road
- Difficulty Level: Easy
- Question URL: https://app.codility.com/programmers/lessons/5-prefix_sums/passing_cars/
- Time Complexity:
Solution:
Solution to Codility's Passing Cars problem which is from the Codility Lesson 5: Prefix Sums and, is solved in Java 8 with 100% performance and correctness scores. The goal here is to count the number of passing cars on the road You can find the question of this PassingCars problem in the Codility website.
package Codility.Lesson5;
import java.util.*;
public class PassingCars {
public static void main(String[] args) {
// TODO Auto-generated method stub
int input[] = { 3, 4, 4, 6, 1, 4, 4 };
int result = solution(input);
System.out.println(result);
}
public static int solution(int[] A) {
// write your code in Java SE 8
int zeros = 0;
int carPasses = 0;
for (int i = 0; i < A.length; i++) {
if (A[i] == 0) {
zeros++;
} else if (A[i] == 1) { // for every 1 - there will be an extra car pass for ALL the 0's that came
// before it
carPasses += zeros;
if (carPasses > 1000000000) {
return -1;
}
}
}
return carPasses;
}
}