I thought of a different approach to the question, not sure if it will work.
My Solution
Idea: The final score that we get = sum - sum_deleted, which means that we are trying to minimize the sum of integers that we deleted.
Each time we choose a_k, we delete deleted[a_k] = count[a_{k-1}] * a_{k-1} + count[a_{k+1}] * a_{k+1}, where count[a_k] denotes the number of a_k. So is it possible to greedily search for the minimal deleted[a_k] each time and delete them? I am not sure if this will lead to optimal solution.
Official Solution
Use dynamic programming. For each integer a_k, we either choose it or delete it. So we can do dp from the largest integer that we have:
- Suppose
dp[k]denotes the largest score that we can have with the array of integers given and delete all the integers larger than k. So for test case
1 | 10 |
dp[2] would denote the largest score that we can get from array 1 2 2
dp[k]can be degraded to situation where either we choosekor not choosek. If we choosek, thenk-would also be deleted, which would bedp[k-2] + cnt[k] * k. If we don’t choosek, then it would be the same asdp[k-1]. So the dp formula:
dp[k] = max({dp[k-2] + cnt[k] * k, dp[k-1]})
1 |
|
Thoughts
I didn’t thought about dynamic programming ways to solve this problem. I guess the best way to come up with a dp solution is to degrade the question to easier scenarios. I think this question is actually a typical “choose or not” type of dp problem.
Also, still not sure whether my solution will work. I will think about it when I am better :D