-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathResult.java
More file actions
50 lines (38 loc) · 1.46 KB
/
Result.java
File metadata and controls
50 lines (38 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package hackrank.algorithm.implement.stick;
import java.util.ArrayList;
import java.util.List;
/**
* @see <a href="https://www.hackerrank.com/challenges/cut-the-sticks">Cut the Sticks</a>
*/
public class Result {
private static final int STICK_MAX_LENGTH = 1000;
/**
* @param arr List of stick lengths
* @return List with number of sticks left after each iteration of cuts
*/
public static List<Integer> cutTheSticks(List<Integer> arr) {
// add an extra one to array size to keep things "nicer". First element at index 0 will
// never be used because a stick can never start out with 0 length
int[] lengthCounts = new int[STICK_MAX_LENGTH + 1];
int minLength = Integer.MAX_VALUE;
int maxLength = Integer.MIN_VALUE;
for (Integer stickLength : arr) {
if (stickLength < minLength) {
minLength = stickLength;
}
if (stickLength > maxLength) {
maxLength = stickLength;
}
lengthCounts[stickLength]++; // use stick length as array index and array value is the count
}
int sticksLeft = arr.size();
List<Integer> cutIterations = new ArrayList<>();
for (int i = minLength; i <= maxLength; i++) {
if (lengthCounts[i] != 0) {
cutIterations.add(sticksLeft);
sticksLeft -= lengthCounts[i];
}
}
return cutIterations;
}
}