Minimum Rounds to Complete All Tasks LeetCode solution in Java

1
/**
2
* Each round, we can complete either 2 or 3 tasks of the same difficulty level Time: O(n) Space:
3
* O(n)
4
*/
5
class Solution {
6
public int minimumRounds(int[] tasks) {
7
int round = 0;
8
Map<Integer, Integer> taskMap = new HashMap<>(); // map of <task, number of each task>
9
for (int i = 0; i < tasks.length; i++) {
10
taskMap.put(tasks[i], taskMap.getOrDefault(tasks[i], 0) + 1);
11
}
12

13
for (Map.Entry<Integer, Integer> entry : taskMap.entrySet()) {
14
if (entry.getValue() == 1) {
15
return -1; // we cannot complete if there is only 1 task
16
}
17
// try to take as many 3's as possible
18
round += entry.getValue() / 3;
19

20
/*
21
We can have 1 or 2 tasks remaining. We're not supposed to take task of count 1, but we can 'borrow' 1 from the previous
22
ex. [5,5,5,5,5,5,5] -> [5,5,5][5,5,5][5]
23
In this example, treat the last [5,5,5], [5] as [5,5], [5,5]
24
*/
25
if (entry.getValue() % 3 != 0) {
26
round++;
27
}
28
}
29
return round;
30
}
31
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0