Skip to content

Commit

Permalink
Create Minimize the heights I
Browse files Browse the repository at this point in the history
  • Loading branch information
dishathakurata authored Nov 23, 2024
1 parent 5648b7a commit b68deae
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions Minimize the heights I
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
//Minimize the heights I

import java.io.*;
import java.util.*;

public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine().trim());

while(t-- > 0) {
int k = Integer.parseInt(br.readLine().trim());
String input = br.readLine().trim();
String[] tokens = input.split(" ");
int[] arr = new int[tokens.length];

for(int i = 0; i < tokens.length; i++) {
arr[i] = Integer.parseInt(tokens[i]);
}

Solution ob = new Solution();

int res = ob.getMinDiff(k, arr);

System.out.println(res);
System.out.println("~");
}
}
}

class Solution {
public int getMinDiff(int k, int[] arr) {
int n = arr.length;

Arrays.sort(arr);

int diff = 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);

diff = Math.min(diff, max - min);
}

return diff;
}
}

0 comments on commit b68deae

Please sign in to comment.