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 INPUT nums = [2, 1, 3] 2 idx 0 1 idx 1 3 idx 2 Possible Values (each can +0 or +1) 2 or 3 1 or 2 3 or 4 Goal: Find longest consecutive sequence after modifications ALGORITHM STEPS 1 Sort Array [2,1,3] --> [1,2,3] 2 Use Set/DP Track reachable values 3 Process Each Check n and n+1 options 4 Extend Sequence Update max length Processing: 1 --> 2 --> 3 --> 4 1+1=2, 2+1=3, 3+1=4 Forms: 2, 3, 4 Consecutive! Length=3 FINAL RESULT Optimal Selection: 2 3 4 1+1 3+0 3+1 Consecutive Check: 3-2=1 [OK] 4-3=1 [OK] OUTPUT 3 Maximum consecutive elements = 3 Key Insight: Each element can become n or n+1. Sort the array, then use dynamic programming with a set to track which consecutive ending values are reachable. For each element, extend the longest sequence ending at (value-1) or value. Time: O(n log n), Space: O(n). TutorialsPoint - Maximize Consecutive Elements in an Array After Modification | Optimal Solution
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