Skip to content

Commit

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

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

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

while(tc-- > 0) {
String[] inputLine = br.readLine().trim().split(" ");
int k = Integer.parseInt(inputLine[0]);

inputLine = br.readLine().trim().split(" ");

if (inputLine == null || inputLine.length == 0) {
System.out.println("Invalid input");
continue;
}

int[] arr = new int[inputLine.length];

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

int ans = new Solution().getMinDiff(arr, k);
System.out.println(ans);
}
}
}

class Solution {
int getMinDiff(int[] arr, int k) {
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);

if(min < 0) {
continue;
}

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

return diff;
}
}

0 comments on commit 5648b7a

Please sign in to comment.