Skip to content

New Solution to the Passing Car Problem #1

@jahan-paisley

Description

@jahan-paisley

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}));
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions