Skip to content

Commit 35db5cb

Browse files
authored
Add files via upload
1 parent 2cfcffe commit 35db5cb

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

minHeight.java

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
//Q. Minimize the Heights
2+
package lbDsaSheet;
3+
4+
import java.io.*;
5+
import java.util.*;
6+
7+
//Given array contains the height of the towers
8+
//case1: Subtract the shortest height from the tallest height given then minimise the result futher
9+
//this is to be done by using the given value of k
10+
//k can be added or subtracted to any given tower's height
11+
public class minHeight {
12+
public static void main(String[] args) throws Exception {
13+
14+
int k = 2, n = 4;
15+
int arr[] = { 1, 5, 8, 10 };
16+
}
17+
18+
int getMinDiff(int[] arr, int n, int k) {
19+
// code here
20+
21+
// base case
22+
if (n == 1)
23+
return 0;
24+
25+
Arrays.sort(arr);
26+
27+
// max difference
28+
int diff = arr[n - 1] - arr[0];
29+
30+
int min, max;
31+
32+
for (int i = 1; i < n; i++) {
33+
34+
// After the operation, the resultant array should not contain any negative integers.
35+
if (arr[i] - k < 0)continue;
36+
max = Math.max(arr[i - 1] + k, arr[n - 1] - k); // subtracting k from largest element and comparing the max from the rest of the elements after subtracting k from them
37+
min = Math.min(arr[0] + k, arr[i] - k); // adding k to the smallest element and comparing the min from the rest of the elements after adding k to them
38+
39+
diff = Math.min(diff, max - min);
40+
}
41+
return diff;
42+
43+
44+
45+
}
46+
System.out.println(diff);
47+
}

0 commit comments

Comments
 (0)