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.
1#include <iostream>
2#include <vector>
3#include <algorithm>
4
5using namespace std;
6
7int maxElementAfterDecreasingAndRearranging(vector<int>& arr) {
8 sort(arr.begin(), arr.end());
9 arr[0] = 1;
10 for (size_t i = 1; i < arr.size(); i++) {
11 arr[i] = min(arr[i], arr[i-1] + 1);
12 }
13 return arr.back();
14}
15
16int main() {
17 vector<int> arr = {100, 1, 1000};
18 cout << maxElementAfterDecreasingAndRearranging(arr);
19 return 0;
20}
In C++, we use the sort
function from the Standard Library to sort the array. We then iterate through the sorted array, setting the first element to 1 and ensuring each subsequent element is adjusted appropriately.
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 this Java solution, an iteration across the input array fills the count array, tracking how often each value appears. This count data helps set the elements to their maximum feasible values while respecting the constraints.