Codility: Peaks Solution

Lesson 10 Prime and Composite Numbers

Implementation

1function solution(A) {
2 const N = A.length
3 const isPeak = (a, b, c) => a < b && b > c
4
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 continue
15 }
16 let quotient = 0
17 const numberOfBlocks = Math.floor(N / blockSize)
18 let valid = true
19 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 peak
26 if (quotient !== numberOfBlocks) {
27 valid = false
28 }
29 if (valid) return numberOfBlocks
30 }
31 return 0
32}

References

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

Comments

Loading comments...

Tags

codility

Next Post

Codility: MinPerimeterRectangle

Jan 26, 2021

Lesson 10 Prime and Composite Numbers

Previous Post

HoningJS

Search Posts