Flags, the famous code challenge in Codility.
I've tried several times and I'm pretty sure the bug is inside the function "CheckFlags" I've also tried the official solution provided by Codility and got 100% eventually. However, I cannot figure out why my checking algorithm fails and there are only three failed test data (check test report).
function solution(A) { let peakIndex = []; let peakCount = 0; for (let i = 1; i < A.length-1; i++) { if (A[i-1] < A[i] && A[i] > A[i+1]) { peakIndex[peakCount] = i; peakCount++; } } if (peakCount === 0 || peakCount === 1) return peakCount; let left = 2; let right = peakCount; let result; while(right >= left) { // binary search let flags = Math.floor((left+right)/2) if (!CheckFlags(peakIndex, flags)) { right = flags - 1; } else { result = flags; left = flags + 1; } } return result; } function CheckFlags (peakIndex, flags) { let flagCount = 1; let flagIndex = new Array(flags); flagIndex[0] = 0; // always include the first flag for (let peakIter = 1; peakIter < peakIndex.length && flagCount <= flags; peakIter++) { if (peakIndex[peakIter] - flagIndex[flagCount - 1] >= flags) { flagIndex[flagCount] = peakIndex[peakIter]; flagCount++; if (flagCount === flags) return true; } } return false; }