From 5648b7ae151f7fa4b23fbee1ccbfb5a36ad5aab8 Mon Sep 17 00:00:00 2001 From: Disha Thakurata <146114938+dishathakurata@users.noreply.github.com> Date: Sat, 23 Nov 2024 10:33:35 +0530 Subject: [PATCH] Create Minimize the heights II --- Minimize the heights II | 58 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Minimize the heights II diff --git a/Minimize the heights II b/Minimize the heights II new file mode 100644 index 0000000..ecf32e1 --- /dev/null +++ b/Minimize the heights II @@ -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; + } +}