Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

QUESTION LINK-LINK

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.

 Iterate through the Array:

 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.

 Return the Result: Finally, return the minimized maximum difference.

CODE IN JAVA-
class Solution {

int getMinDiff(int[] arr, int n, int k) {

// 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:

int getMinDiff(int arr[], int n, int k) {

sort(arr, arr + n);

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 = std::min(smallest, arr[i+1] - k);

max = std::max(largest, arr[i] + k);

if (min < 0) continue;

ans = std::min(ans, max - min);

return ans;

};

You might also like