Maximize Consecutive Elements in an Array After Modification

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.

Example 1
Inputnums = [2,1,5,1,1]
Output3
Increasing the elements at indices 0 and 3 gives nums = [3, 1, 5, 2, 1], from which [1, 2, 3] can be selected, and no larger consecutive selection is possible.
Example 2
Inputnums = [1,4,7,10]
Output1
No two elements can be modified to form a consecutive selected set, so the maximum consecutive selection has size 1.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^6

Asked at 1 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate