Sponsored
Sponsored
This approach involves sorting the array first. After sorting, we iterate over the array from the first element onwards, setting each element to be the minimum between its current value and the value of the previous element plus 1. This ensures the conditions are met, i.e., the first element is 1 and the difference between adjacent elements is <= 1.
Time Complexity: O(n log n) due to sorting.
Space Complexity: O(1) as we modify the array in place.
1import java.util.Arrays;
2
3public class Solution {
4 public static int maxElementAfterDecreasingAndRearranging(int[] arr) {
5 Arrays.sort(arr);
6 arr[0] = 1;
7 for (int i = 1; i < arr.length; i++) {
8 arr[i] = Math.min(arr[i], arr[i-1] + 1);
9 }
10 return arr[arr.length - 1];
11 }
12
13 public static void main(String[] args) {
14 int[] arr = {100, 1, 1000};
15 System.out.println(maxElementAfterDecreasingAndRearranging(arr));
16 }
17}
In Java, we use Arrays.sort
to sort the array. After sorting, the procedure of setting each element based on the condition is followed as described, using Math.min
to ensure the constraints are met.
This approach leverages the counting sort technique which avoids sorting the entire array directly. Instead, it uses a frequency array to count occurrences of each element. Then, reconstruct the final array by checking counts and adjusting values accordingly to ensure the maximum element is achieved while meeting the constraints.
Time Complexity: O(n), due to the pass over the array to count elements.
Space Complexity: O(n), primarily due to the count array.
The Python solution utilizes a list of zeros to tally occurrences. By counting the array elements and incrementing the corresponding index in the count list, we construct an array meeting the challenge's demands.