Intuition
Sort the values, then for each target value keep the longest run of consecutive values ending there; every number can play its own value or that value plus one.
Explanation
Idea
Each number may be left alone or increased by exactly one, so a number x can cover the target value x or the target value x + 1. We want the longest chain of consecutive target values t, t+1, t+2, ... where every target in the chain is covered by a distinct number.
Sort the array and process numbers from small to large. Keep a map dp where dp[v] is the length of the longest consecutive chain that ends at target value v, using numbers seen so far.
For the current number num:
- Use it bumped up, as
num + 1: it extends a chain that ended atnum. Sodp[num + 1] = dp[num] + 1. - Use it as itself,
num: it extends a chain that ended atnum - 1. Sodp[num] = dp[num - 1] + 1.
Step 1 must run before step 2. Reading the old dp[num] first lets a different (earlier) number supply the value num, which is exactly what makes duplicates line up into a longer chain.
Worked example
nums = [2,1,5,1,1] → sorted [1,1,1,2,5].
num = 1:dp[2] = dp[1] + 1 = 1, thendp[1] = dp[0] + 1 = 1. best = 1.num = 1:dp[2] = dp[1] + 1 = 2(one1stays, this1becomes2), thendp[1] = 1. best = 2.num = 1:dp[2] = dp[1] + 1 = 2,dp[1] = 1. best = 2.num = 2:dp[3] = dp[2] + 1 = 3(chain1,2,3),dp[2] = dp[1] + 1 = 2. best = 3.num = 5:dp[6] = 1,dp[5] = 1. best stays 3.
Answer: 3. For example, turn two of the ones into 2 and 3 to get sorted [1,2,3].
Complexity
- Time: O(n log n) for the sort, plus O(n) for the scan.
- Space: O(n) for the map.
Implementation
import java.util.*;
class Solution {
public int maxSelectedElements(int[] nums) {
Arrays.sort(nums);
Map<Integer, Integer> dp = new HashMap<>();
int ans = 1;
for (int num : nums) {
dp.put(num + 1, dp.getOrDefault(num, 0) + 1);
dp.put(num, dp.getOrDefault(num - 1, 0) + 1);
ans = Math.max(ans, Math.max(dp.get(num), dp.get(num + 1)));
}
return ans;
}
}