Maximize Consecutive Elements in an Array After Modification - Problem
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 most 1.
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 the maximum number of elements that you can select.
Input & Output
Example 1 — Basic Consecutive Sequence
$
Input:
nums = [2,1,3]
›
Output:
3
💡 Note:
We can modify the array to [2,2,3] or [3,2,3], giving us the consecutive sequence [1,2,3] which has length 3.
Example 2 — Optimal Selection
$
Input:
nums = [1,4,7]
›
Output:
2
💡 Note:
We can modify to get [2,4,7], [1,5,7], or [1,4,8]. Best consecutive sequence we can form is length 2, like [4,5] from [1,5,7].
Example 3 — All Same Values
$
Input:
nums = [3,3,3,3]
›
Output:
4
💡 Note:
We can keep all as [3,3,3,3] or modify some to [3,3,4,4], giving consecutive sequences like [3,4] but optimal is all same value.
Constraints
- 1 ≤ nums.length ≤ 105
- 1 ≤ nums[i] ≤ 106
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Original array where each element can be increased by at most 1
2
Possible Values
Each element x can become either x or x+1, creating frequency map
3
Find Consecutive
Find longest consecutive sequence we can form within element limit
Key Takeaway
🎯 Key Insight: Each element can become x or x+1, so count all possible values and find the longest consecutive sequence achievable within the total element count limit.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code