Intuition¶
We may rearrange freely and only decrease values, so the best order is non-decreasing. Once sorted, the smallest element becomes 1, and every later element can be at most one greater than its predecessor. To maximize the final maximum, each position should stay as large as the constraint allows.
Approach: Sorting + Greedy¶
- Sort
arrin non-decreasing order. - Set
arr[0] = 1. - Scan left to right: if
arr[i + 1] > arr[i] + 1, cap it toarr[i] + 1. - Return the last element, which is the largest value in the valid rearrangement.
Complexity¶
- Time complexity: O(n log n) for sorting.
- Space complexity: O(log n) for the sort stack (in-place sort).
Code¶
Go¶
import "sort"
func maximumElementAfterDecrementingAndRearranging(arr []int) int {
sort.Ints(arr)
arr[0] = 1
for i := range len(arr) - 1 {
if arr[i+1] > 1+arr[i] {
arr[i+1] = arr[i] + 1
}
}
return arr[len(arr)-1]
}