Getting WA in testcases 2 to 6

Getting WA in testcases 2 to 6.
Kindly help.

Hey @aman89533
Please explain your logic :

i have used dictionary d for storing count

l is list that is sorted and don’t contain duplicates like [1,2,3]

i have used [0]+list for creating 1 based indexing…just for ease

dp is array for storing results that is initialized to all zero

and then used,
DP[i] = max(l[i]*d[i]+DP[i-2] , DP[i-1] )

Dp[1]=d[1]
for i in range(2,l[-1]+1):
dp[i]=max(dp[i-1],dp[i-2]+d[i]*i)

Also update ur dp size array to l[-1]+1

Try this it should work ,if not then let me know i will check on PC

all passed sir

i have used count=0 for missing numbers and it worked.

Thank you very much sir.

from collections import Counter
n=int(input())
l=list(map(int,input().split()))
d=dict(Counter(l))
m=max(l)
l=[0]+l
dp=[0 for _ in range(m+5)]
if 1 in d:
dp[1]=d[1]
else:
dp[1]=0
m=max(l)
for i in range(2,m+1):
if i in d:
count=d[i]
dp[i]=max(dp[i-1],dp[i-2]+i*count)
else:
dp[i]=max(dp[i-1],dp[i-2]) # count is 0 if element not in dictionry key
print(dp[m])

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.