# Codility: MaxCounters Solution

*Lesson 4 Counting Elements*

1function solution(X, A) {2 let res = Array(X).fill(0)3 let max = 04 let latestMax = 05 for (const a of A) {6 if (1 <= a && a <= X) {7 if (res[a - 1] < latestMax) {8 res[a - 1] = latestMax9 }10 res[a - 1] += 111 if (res[a - 1] > max) {12 max = res[a - 1]13 }14 } else {15 latestMax = max16 }17 }18 for (const [i, r] of res.entries()) {19 if (r < latestMax) {20 res[i] = latestMax21 }22 }23 return res24}

## 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.