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

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

Codility: MinPerimeterRectangle

Lesson 10 Prime and Composite Numbers

HoningJS

Search Posts