Skip to content

Instantly share code, notes, and snippets.

@ernestlv
Created February 19, 2018 02:19
Show Gist options
  • Save ernestlv/2fda618c7c24d8b024a9441e1e46f47e to your computer and use it in GitHub Desktop.
Save ernestlv/2fda618c7c24d8b024a9441e1e46f47e to your computer and use it in GitHub Desktop.
Codility Silver Award for the Ferrum 2018 Challenge
function solution(A) {
var red = A => A.reduce((res, val) => res+val);
for (i=0; i<A.length; i++){
var z = i
for (j=0, z=i; j<=i; j++, z--){
x = red(A.slice(j, A.length-z));
if (x>=0) return A.length-z-j;
}
}
return 0;
}
@ernestlv
Copy link
Author

You are given an array A consisting of the integers −1, 0 and 1. A slice of that array is any pair of integers (P, Q) such that 0 ≤ P ≤ Q < N. Your task is to find the longest slice of A whose elements yield a non-negative sum.

Write a function:

int solution(int A[], int N);

that, given an array A of length N, consisting only of the values −1, 0, 1, returns the length of the longest slice of A that yields a non-negative sum. If there's no such slice, your function should return 0.

For example, given A = [−1, −1, 1, −1, 1, 0, 1, −1, −1], your function should return 7, as the slice starting at the second position and ending at the eighth is the longest slice with a non-negative sum.

For another example, given A = [1, 1, −1, −1, −1, −1, −1, 1, 1] your function should return 4: both the first four elements and the last four elements of array A are longest valid slices.

Assume that:

    N is an integer within the range [2..100,000];
    each element of array A is an integer within the range [−1..1].

Complexity:

    expected worst-case time complexity is O(N*log(N));
    expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment