Skip to content

Commit 8a1eae7

Browse files
committed
practice session
1 parent 6385463 commit 8a1eae7

2 files changed

Lines changed: 72 additions & 0 deletions

File tree

FileReading.java

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import java.util.*;
2+
3+
import java.io.*;
4+
5+
public class FileReading {
6+
public static void main(String [] args) {
7+
String fileName = "DeleteNodeinaBST.java";
8+
try {
9+
BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName));
10+
String line;
11+
while ((line=bufferedReader.readLine()) != null) {
12+
System.out.println(line);
13+
}
14+
bufferedReader.close();
15+
}
16+
catch(Exception e) {
17+
e.printStackTrace();
18+
}
19+
}
20+
}

Study/AggressiveCows.java

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import java.util.*;
2+
3+
public class AggressiveCows {
4+
public static void main(String [] args) {
5+
Scanner sc = new Scanner(System.in);
6+
int test = sc.nextInt();
7+
while (test-- > 0) {
8+
int n = sc.nextInt();
9+
int cows = sc.nextInt();
10+
int [] stalls = new int [n];
11+
for (int i = 0; i < n; i++) {
12+
stalls[i] = sc.nextInt();
13+
}
14+
System.out.println(maxDistance(stalls, cows, n));
15+
}
16+
sc.close();
17+
}
18+
19+
private static int maxDistance(int [] stalls, int cows, int n) {
20+
if (stalls == null || stalls.length == 0) {
21+
return 0;
22+
}
23+
Arrays.sort(stalls);
24+
int low = 1;
25+
int high = (int)(1e9 + 7);
26+
int maxCowDistance = -1;
27+
while (low <= high) {
28+
int middle = low + (high - low) / 2;
29+
if (canCowBePlaced(stalls, cows, middle)) {
30+
maxCowDistance = middle;
31+
low = middle + 1;
32+
}
33+
else {
34+
high = middle - 1;
35+
}
36+
}
37+
return maxCowDistance;
38+
}
39+
40+
private static boolean canCowBePlaced(int [] stalls, int cows, int minDistance) {
41+
int cowCount = 1;
42+
int previousPositionOfCow = stalls[0];
43+
for (int i = 1; i < stalls.length; i++) {
44+
int currentStallPos = stalls[i];
45+
if (currentStallPos - previousPositionOfCow >= minDistance) {
46+
cowCount++;
47+
previousPositionOfCow = currentStallPos;
48+
}
49+
}
50+
return cowCount >= cows;
51+
}
52+
}

0 commit comments

Comments
 (0)