-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
f569293
commit 5648b7a
Showing
1 changed file
with
58 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |