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.
1using System;
2
3class Solution {
4 public static int MaxElementAfterDecreasingAndRearranging(int[] arr) {
5 Array.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 static void Main() {
14 int[] arr = {100, 1, 1000};
15 Console.WriteLine(MaxElementAfterDecreasingAndRearranging(arr));
16 }
17}
In C#, we use Array.Sort
followed by iterating over the array to ensure each element is at most the previous element plus one. The Math.Min
function is used to maintain the required conditions.
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.
In C, we use calloc
to create a count array which logs the frequency of each element. The counting concludes, and array values are adjusted using the count data structure to maximize the array while meeting the constraints.