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
Maximize Consecutive Elements: [2,1,3] → 3Step 1: Input Array213Step 2: Possible Values (+0 or +1)2→2,31→1,23→3,4Step 3: Count Frequencies1:12:23:24:1Consecutive: 2→3But we can do better! Check 1→2→3:1:12:23:2Maximum Length: 3
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.
Asked in
Google 25 Meta 20 Amazon 15 Microsoft 12
23.0K Views
Medium Frequency
~25 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen