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 Rearranging INPUT Original Array: 2 1 3 5 4 i=0 i=1 i=2 i=3 i=4 Constraints: 1. arr[0] must be 1 2. |arr[i] - arr[i-1]| <= 1 Unsorted Values: ALGORITHM STEPS 1 Sort Array Arrange in ascending order 1 2 3 4 5 2 Set First = 1 First element must be 1 3 Build Staircase Each step: min(arr[i], prev+1) 1 2 3 4 5 4 Return Max Last element is maximum FINAL RESULT Optimal Array: 1 2 3 4 5 Adjacent Differences: |2-1|=1 |3-2|=1 |4-3|=1 |5-4|=1 All differences <= 1 [OK] OUTPUT 5 Maximum achievable staircase height = 5 VERIFIED [OK] Key Insight: After sorting, the maximum possible value equals the length of the longest valid staircase starting from 1. Since we can only decrease values, sorting ensures we maximize at each position: arr[i] = min(arr[i], arr[i-1]+1). Time: O(n log n) for sorting | Space: O(1) excluding sort space TutorialsPoint - Maximum Element After Decreasing and Rearranging | Optimal Greedy - Maximum Staircase Height
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