Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New Solution to the Passing Car Problem #1

Open
jahan-paisley opened this issue Mar 23, 2021 · 0 comments
Open

New Solution to the Passing Car Problem #1

jahan-paisley opened this issue Mar 23, 2021 · 0 comments

Comments

@jahan-paisley
Copy link

jahan-paisley commented Mar 23, 2021

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}));
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant