Professional Documents
Culture Documents
12 JUNE 2024
12 JUNE 2024
APPROACH-
Sort the Array: The first step is to sort the array. This makes it easier to handle the
minimum and maximum values after the modifications.
Initial Difference: Calculate the initial difference between the maximum and minimum
values in the sorted array, i.e., arr[n-1] - arr[0].
Adjust Bounds: After sorting, the smallest possible value (considering adding kkk) would
be arr[0] + k, and the largest possible value (considering subtracting kkk) would be
arr[n-1] - k.
For each element in the array (except the last one), calculate the possible new
minimum (min) and maximum (max) values:
o min is the minimum of smallest and the current element reduced by kkk.
o max is the maximum of largest and the current element increased by kkk.
If the new minimum value is negative, skip to the next iteration as heights can't be
negative.
Update the answer with the minimum value of the current answer and the difference
between max and min.
CODE IN JAVA-
class Solution {
// code here
Arrays.sort(arr);
int ans=arr[n-1]-arr[0];
int smallest=arr[0]+k;
int largest=arr[n-1]-k;
int min,max;
for(int i=0;i<n-1;i++)
{
min=Math.min(smallest,arr[i+1]-k);
max=Math.max(largest,arr[i]+k);
if(min<0) continue;
ans=Math.min(ans,max-min);
}
return ans;
CODE IN C++
class Solution {
public:
return ans;
};