Bad performance in Java exercise -


i'm doing tests in java warm up, , made one:

a non-empty zero-indexed array consisting of n integers given. consecutive elements of array represent consecutive cars on road.

array contains 0s and/or 1s:

0 represents car traveling east, 1 represents car traveling west. goal count passing cars. pair of cars (p, q), 0 ≤ p < q < n, passing when p traveling east , q traveling west.

for example, consider array such that:

a[0] = 0 a[1] = 1 a[2] = 0 a[3] = 1 a[4] = 1 have 5 pairs of passing cars: (0, 1), (0, 3), (0, 4), (2, 3), (2, 4).

write function:

class solution { public int solution(int[] a); }

that, given non-empty zero-indexed array of n integers, returns number of pairs of passing cars.

the function should return −1 if 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 function should return 5, explained above.

assume that:

n integer within range [1..100,000]; each element of array integer can have 1 of following values: 0, 1. complexity:

expected worst-case time complexity o(n); expected worst-case space complexity o(1), beyond input storage (not counting storage required input arguments). elements of input arrays can modified.

my code follows:

public int solution(int[] a) {         // write code in java se 8         int result = 0;         long mult = 0;          for(int value : a){              if(value == 0){                 mult ++;                     }             else {                 result += mult;             }         }          return result;     } 

the link result one: https://codility.com/demo/results/trainingfff4bs-az3/

if link die, result said:

performance tests

▶ medium_random random, length = ~10,000 ✔ok ▶ large_random random, length = ~100,000 ✘wrong answer got 1248768710 expected -1 ▶ large_big_answer 0..01..1, length = ~100,000 ✘wrong answer got -1794967296 expected -1 ▶ large_alternate 0101..01, length = ~100,000 ✘wrong answer got 1250025000 expected -1 ▶ large_extreme large test 1s/0s, length = ~100,000 ✔ok

any ideas wrong in code?.

your rules say,

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

and don't test condition. ternary operation , like

return result > 1000000000 ? -1 : result; 

or (debateably) more readable

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

and improved performance might add test like

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

Comments