Skip to content

Commit 23eb148

Browse files
committed
add: CuttingWood
1 parent fac15f2 commit 23eb148

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

java/Binary Search/CuttingWood.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import java.util.Arrays;
2+
3+
public class CuttingWood {
4+
public int cuttingwood(int[] heights, int k) {
5+
int left = 0;
6+
int right = Arrays.stream(heights).max().getAsInt();
7+
while (left < right) {
8+
// Bias the midpoint to the right during the upper-bound binary
9+
// search.
10+
int mid = (left + right) / 2 + 1;
11+
if (cutsEnoughWood(mid, k, heights)) {
12+
left = mid;
13+
} else {
14+
right = mid - 1;
15+
}
16+
}
17+
return right;
18+
}
19+
20+
// Determine if the current value of 'H' cuts at least 'k' meters of
21+
// wood.
22+
private boolean cutsEnoughWood(int H, int k, int[] heights) {
23+
int woodCollected = 0;
24+
for (int height : heights) {
25+
if (height > H) {
26+
woodCollected += (height - H);
27+
}
28+
}
29+
return woodCollected >= k;
30+
}
31+
}

0 commit comments

Comments
 (0)