function boredom(a, n)
// Build frequency count cnt
cnt := array of zeros up to max(a)
M := 0
for i from 1 to n:
cnt[a[i]] := cnt[a[i]] + 1
if a[i] > M then M := a[i]
// DP with base cases
dp := array of size M + 1
dp[0] := 0
dp[1] := cnt[1]
// Fill using transition
for i from 2 to M:
take := dp[i - 2] + i * cnt[i]
skip := dp[i - 1]
dp[i] := max(skip, take)
return dp[M]
You first count frequencies, then use to fill all values up to .
Time: . Space complexity: where M is the maximum element.