Poor performance in Java exercise

I am doing some tests in Java to warm up, and I just did this:

Given a non-empty null-indexed array A, consisting of N integers. The sequential elements of array A are sequential cars on the road.

Array A contains only 0s and / or 1s:

0 is a car traveling east, 1 is a car traveling west. The goal is to count passing cars. We say that a pair of cars (P, Q), where 0≤P <Q <N, passes when P moves east and Q travels west.

For example, consider an array A such that:

A [0] = 0 A [1] = 1 A [2] = 0 A [3] = 1 A [4] = 1 We have five pairs of passing cars: (0, 1), (0, 3), (0, 4), (2, 3), (2, 4).

Write a function:

class Solution {public int solution (int [] A); }

which, given the non-empty zero index A of N integers, returns the number of pairs of passing cars.

The function should return -1 if the number of pairs of passing cars exceeds 1,000,000,000.

For example, given:

A [0] = 0 A [1] = 1 A [2] = 0 A [3] = 1 A [4] = 1 the function should return 5, as explained above.

Let's pretend that:

N is an integer in the range [1.000000]; each element of array A is an integer that can have one of the following values: 0, 1. Complexity:

expected worst-case time complexity - O (N); expected worst-case space is O (1) complexity, outside of input storage (not counting storage required for input arguments). Elements of input arrays can be changed.

My code is as follows:

public int solution(int[] A) {
        // write your code in Java SE 8
        int result = 0;
        long mult = 0;

        for(int value : A){

            if(value == 0){
                mult ++;        
            }
            else {
                result += mult;
            }
        }

        return result;
    }

: https://codility.com/demo/results/trainingFFF4BS-AZ3/

, :

▶ medium_random random, length = ~ 10000 ✔ OK ▶ large_random random, = ~ 100 000 ✘ 1248768710 -1 ▶ large_big_answer 0..01..1, = ~ 100 000 ✘ -1794967296 -1 ▶ large_alternate 0101..01, = ~ 100 000 ✘ 1250025000 -1 ▶ _ 1s/0s, = ~ 100 000 ✔ OK

, ?

+4
1

,

-1, 1 000 000 000.

. -

return result > 1000000000 ? -1 : result;

()

if (result > 1000000000) {
    return -1;
}
return result;

,

for (int value : A) {
    if (value == 0) {
        mult++;
    } else {
        result += mult;
        if (result > 1000000000) {
            return -1;
        }
    }
}
return result;
+4

Source: https://habr.com/ru/post/1609052/


All Articles