MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / CuttingWood

Class CuttingWood

java/Binary Search/CuttingWood.java:3–31  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1import java.util.Arrays;
2
3public 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 - left) / 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}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected