CodilityInJava icon indicating copy to clipboard operation
CodilityInJava copied to clipboard

New Solution to the Passing Car Problem

Open jahan-paisley opened this issue 4 years ago • 0 comments

Hi @cutajarj, I came up with a different solution for Passing Car problem and thoguht that you might be interested to check it out. The only improvement is that the space complexity is O(1).

public class Solution10CarCollision {
    public int solution(int[] A) {
        int factor = 0;
        int sum = 0;
        for (int i = 0; i < A.length; i++) {
            if (A[i] == 0)
                factor += 1;
            if (A[i] == 1 && factor != 0)
                sum += factor;
            if (sum > 1_000_000_000)
                return -1;
        }
        return sum;
    }

    @Test
    public void test_solution() throws Exception {
        Assertions.assertEquals(5, solution(new int[]{0, 1, 0, 1, 1}));
        Assertions.assertEquals(6, solution(new int[]{0, 1, 0, 1, 0, 1}));
    }
}

jahan-paisley avatar Mar 23 '21 20:03 jahan-paisley