Codility: Peaks Solution

Lesson 10 Prime and Composite Numbers

Implementation

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}function solution(A) {2  const N = A.length3  const isPeak = (a, b, c) => a < b && b > c4
5  const peaks = []6  for (let i = 1; i < N - 1; i++) {7    if (isPeak(A[i - 1], A[i], A[i + 1])) {8      peaks.push(i)9    }10  }11
12  for (let blockSize = 1; blockSize <= N; blockSize++) {13    if (N % blockSize !== 0) {14      continue15    }16    let quotient = 017    const numberOfBlocks = Math.floor(N / blockSize)18    let valid = true19    for (const peakIndex of peaks) {20      if (Math.floor(peakIndex / blockSize) === quotient) {21        quotient++22      }23    }24
25    // make sure each block have at least 1 peak26    if (quotient !== numberOfBlocks) {27      valid = false28    }29    if (valid) return numberOfBlocks30  }31  return 032}```

References

https://rafal.io/posts/codility-peaks.html

codility

Next Post

Codility: MinPerimeterRectangle

Jan 26, 2021

Lesson 10 Prime and Composite Numbers

Search Posts