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
arrmust 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]) <= 1for eachiwhere1 <= i < arr.length(0-indexed).abs(x)is the absolute value ofx.
There are 2 types of operations that you can perform any number of times:
- Decrease the value of any element of
arrto a smaller positive integer. - Rearrange the elements of
arrto 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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code