Codility flags challenge (looked at other posts here, but it didnt help)
Following code got 40% and it fails on medium and big inputs. Input size probably does not matter, but in those inputs are some special cases, where my code fails and Im not able to find out what those cases are.
Here is the task https://codility.com/programmers/lessons/8
Here is my result https://codility.com/demo/results/demoZHJB56-RHM/
function solution(A) { var mountains = A.length; var prevMountain; var currentMountain; var nextMountain; var i; var peaks = []; var currentPeak; var prevPeak; var output = 0; var gap; for(i = 1; i < (A.length-1); i++) { prevMountain = A[i-1]; currentMountain = A[i]; nextMountain = A[i+1]; if(currentMountain > prevMountain && currentMountain > nextMountain) { peaks.push(i); } } if(peaks.length > 0) { gap = peaks.length; for(i = peaks.length; i >= 1; i--) { currentPeak = peaks[i-1]; prevPeak = peaks[i-2]; if(i === 1){ prevPeak = peaks.length * (-1); } if((currentPeak - prevPeak) < gap) { gap = gap - 1; peaks[i-2] = currentPeak; peaks[i-1] = prevPeak; } else { output++; } } } return output; }