LeetCode 1846. Maximum Element After Decreasing and Rearranging
Intuition
- Set the first element
arr[0]to 1. - Limit the difference of two adjacent elements to 1 or less than 1, which means
arr[i+1]is the same asarr[i]or equal toarr[i] + 1. - Return the maximum possible value in
arr.
Approach
Set
arr[0]to 1 (that’s the rule of this challenge).Set
maxto 1, which represents the maximum possible value in arr is 1.Sort
arrin ascending order.Iterate over
arrfrom the second elementarr[1](becausearr[0]has already been set to 1):- Set
arr[i]tomaxif it’s the same as or higher thanmax, then increasemaxby 1. - Do nothing if
arr[i]is smaller thanmax(which couldn’t happen becausearrhas already been sorted in ascending order).
- Set
Return
max.
Pseudocode of maximumElementAfterDecrementingAndRearranging:
1 | maximumElementAfterDecrementingAndRearranging(arr): |
Complexity
Time complexity: $O(nlogn)$.
- Sorting
arrin ascending order is $O(nlogn)$. - Iterate over
arrto updatearrandmaxis $O(n)$. - Overall complexity is $O(nlogn)$.
- $n$ is the total size of
arr.
- Sorting
Space complexity: $O(1)$.
Code
1 | class Solution { |