#1846
Maximum Element After Decreasing and Rearranging
MediumArrayGreedySortingGreedySorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
The optimal approach involves sorting the array and then adjusting the elements to satisfy the conditions. This is efficient and ensures we maximize the largest element.
⚙️
Algorithm
3 steps- 1Step 1: Sort the array.
- 2Step 2: Initialize the first element to 1.
- 3Step 3: Iterate through the sorted array, adjusting each element to ensure it is at most 1 greater than the previous element.
solution.py8 lines
1# Full working Python code
2def maxElementAfterDecreasing(arr):
3 arr.sort()
4 arr[0] = 1
5 for i in range(1, len(arr)):
6 arr[i] = min(arr[i], arr[i - 1] + 1)
7 return arr[-1]
8ℹ
Complexity note: The time complexity is O(n log n) due to the sorting step, while the adjustment step runs in O(n), making this approach efficient for large arrays.
- 1Sorting the array helps in easily adjusting the elements to meet the conditions.
- 2The maximum possible value is determined by how we can manipulate the sorted array while maintaining the constraints.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.