forked from kothariji/competitive-programming
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path(LEETCODE) Task-Scheduler.java
40 lines (38 loc) · 1.5 KB
/
(LEETCODE) Task-Scheduler.java
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
/**
* Solution to Task Scheduler at Leetcode in Java
* Ref : https://leetcode.com/problems/task-scheduler
* Problem Statement:
* Given a characters array tasks, representing the tasks a CPU needs to do, where each letter represents a different task. Tasks could be done in any order. Each task is done in one unit of time.
* For each unit of time, the CPU could complete either one task or just be idle.
* However, there is a non-negative integer n that represents the cooldown period between two same tasks (the same letter in the array), that is that there must be at least n units of time between any two same tasks.
* Return the least number of units of times that the CPU will take to finish all the given tasks.
Example 1:
Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Explanation:
A -> B -> idle -> A -> B -> idle -> A -> B
There is at least 2 units of time between any two same tasks.
**/
public class Solution {
public int leastInterval(char[] tasks, int n) {
int[] storage = new int[26];
for (char c : tasks) {
storage[(c - 'A')]++;
}
int max = 0;
int count = 1;
for (int num : storage) {
if (num == 0) {
continue;
}
if (max < num) {
max = num;
count = 1;
} else if (max == num) {
count++;
}
}
int space = (n + 1) * (max - 1) + count;
return (space < tasks.length) ? tasks.length : space;
}
}