Created
February 19, 2018 02:19
-
-
Save ernestlv/2fda618c7c24d8b024a9441e1e46f47e to your computer and use it in GitHub Desktop.
Codility Silver Award for the Ferrum 2018 Challenge
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
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:
Complexity: