Dynamic Programming21 sections · 916 units
Open in Course

Codeforces 455A Boredom - Implementation

Complete solution

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 dp[i]=max(dp[i1],dp[i2]+i×cnt[i])dp[i] = \max(dp[i-1], dp[i-2] + i \times \text{cnt}[i]) to fill all values up to dp[M]dp[M].

Time: O(n+M)O(n + M).

Space complexity: O(M)O(M) where M is the maximum element.