Maximum Element After Decreasing and Rearranging - Problem

You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions:

  • The value of the first element in arr must be 1.
  • The absolute difference between any 2 adjacent elements must be less than or equal to 1. In other words, abs(arr[i] - arr[i - 1]) <= 1 for each i where 1 <= i < arr.length (0-indexed). abs(x) is the absolute value of x.

There are 2 types of operations that you can perform any number of times:

  • Decrease the value of any element of arr to a smaller positive integer.
  • Rearrange the elements of arr to be in any order.

Return the maximum possible value of an element in arr after performing the operations to satisfy the conditions.

Input & Output

Example 1 — Basic Case
$ Input: arr = [2,1,3,5,4]
Output: 5
💡 Note: Sort to [1,2,3,4,5]. Build staircase: arr[0]=1, arr[1]=min(2,2)=2, arr[2]=min(3,3)=3, arr[3]=min(4,4)=4, arr[4]=min(5,5)=5. Maximum is 5.
Example 2 — Large Values Need Reduction
$ Input: arr = [100,1,1000]
Output: 3
💡 Note: Sort to [1,100,1000]. Build staircase: arr[0]=1, arr[1]=min(100,2)=2, arr[2]=min(1000,3)=3. Maximum is 3.
Example 3 — Already Optimal
$ Input: arr = [1,2,3,4]
Output: 4
💡 Note: Already sorted and valid staircase. Each element can keep its value: 1→2→3→4. Maximum is 4.

Constraints

  • 1 ≤ arr.length ≤ 105
  • 1 ≤ arr[i] ≤ 109

Visualization

Tap to expand
Maximum Element After Decreasing and RearrangingInput: [2,1,3,5,4]21354Constraints: arr[0] = 1, |arr[i] - arr[i-1]| ≤ 1Optimal: [1,2,3,4,5]12345Perfect staircaseSort → Build staircase greedily → Maximum = 5Output5
Understanding the Visualization
1
Input Array
Given array with constraints to satisfy
2
Sort & Build
Sort and greedily build optimal staircase
3
Maximum Element
Return the highest element in valid arrangement
Key Takeaway
🎯 Key Insight: Sorting enables greedy construction of the tallest valid staircase
Asked in
Google 15 Amazon 12 Facebook 8 Microsoft 6
32.0K Views
Medium Frequency
~15 min Avg. Time
892 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