You are given a 0-indexed array nums consisting of positive integers.
Initially, you can increase the value of any element in the array by at most1.
After that, you need to select one or more elements from the final array such that those elements are consecutive when sorted in increasing order.
For example, the elements [3, 4, 5] are consecutive while [3, 4, 6] and
[1, 1, 2, 3] are not.
Return themaximum number of elements that you can select.
Input: nums =[2,1,5,1,1]Output: 3Explanation: We can increase the elements at indices 0 and 3. The resulting array is nums =[3,1,5,2,1].We select the elements [_**3**_ ,_**1**_ ,5,_**2**_ ,1] and we sort them to obtain [1,2,3], which are consecutive.It can be shown that we cannot select more than 3 consecutive elements.
Since each element can be increased by at most 1, every number in the array can become either itself or itself + 1. To maximize the length of a consecutive sequence, we can try to “shift” as many numbers as possible to fill consecutive slots. By counting the frequency of each possible value (original and original+1), we can use a sliding window to find the longest streak of consecutive numbers.
classSolution {
public:int maxSelectedElements(vector<int>& nums) {
unordered_map<int, int> freq;
for (int x : nums) {
freq[x]++;
freq[x+1]++;
}
vector<int> keys;
for (auto& p : freq) keys.push_back(p.first);
sort(keys.begin(), keys.end());
int ans =0, l =0, sum =0;
for (int r =0; r < keys.size(); ++r) {
if (r >0&& keys[r] != keys[r-1] +1) {
l = r;
sum =0;
}
sum += freq[keys[r]];
while (l < r && sum - freq[keys[l]] >= sum) {
sum -= freq[keys[l++]];
}
ans = max(ans, sum);
}
return ans;
}
};
classSolution {
funmaxSelectedElements(nums: IntArray): Int {
val freq = mutableMapOf<Int, Int>()
for (x in nums) {
freq[x] = freq.getOrDefault(x, 0) + 1 freq[x+1] = freq.getOrDefault(x+1, 0) + 1 }
val keys = freq.keys.sorted()
var ans = 0var l = 0var sum = 0for (r in keys.indices) {
if (r > 0&& keys[r] != keys[r-1] + 1) {
l = r
sum = 0 }
sum += freq[keys[r]]!! ans = maxOf(ans, sum)
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution:
defmaxSelectedElements(self, nums: list[int]) -> int:
from collections import Counter
freq = Counter()
for x in nums:
freq[x] +=1 freq[x+1] +=1 keys = sorted(freq)
ans = l = sum_ =0for r in range(len(keys)):
if r >0and keys[r] != keys[r-1] +1:
l = r
sum_ =0 sum_ += freq[keys[r]]
ans = max(ans, sum_)
return ans
impl Solution {
pubfnmax_selected_elements(nums: Vec<i32>) -> i32 {
use std::collections::HashMap;
letmut freq = HashMap::new();
for&x in&nums {
*freq.entry(x).or_insert(0) +=1;
*freq.entry(x+1).or_insert(0) +=1;
}
letmut keys: Vec<_>= freq.keys().cloned().collect();
keys.sort();
letmut ans =0;
letmut l =0;
letmut sum =0;
for r in0..keys.len() {
if r >0&& keys[r] != keys[r-1] +1 {
l = r;
sum =0;
}
sum += freq[&keys[r]];
ans = ans.max(sum);
}
ans
}
}