|
| 1 | +/* |
| 2 | + * @lc app=leetcode id=621 lang=java |
| 3 | + * |
| 4 | + * [621] Task Scheduler |
| 5 | + * |
| 6 | + * https://leetcode.com/problems/task-scheduler/description/ |
| 7 | + * |
| 8 | + * algorithms |
| 9 | + * Medium (46.16%) |
| 10 | + * Likes: 1885 |
| 11 | + * Dislikes: 332 |
| 12 | + * Total Accepted: 100.8K |
| 13 | + * Total Submissions: 218K |
| 14 | + * Testcase Example: '["A","A","A","B","B","B"]\n2' |
| 15 | + * |
| 16 | + * Given a char array representing tasks CPU need to do. It contains capital |
| 17 | + * letters A to Z where different letters represent different tasks. Tasks |
| 18 | + * could be done without original order. Each task could be done in one |
| 19 | + * interval. For each interval, CPU could finish one task or just be idle. |
| 20 | + * |
| 21 | + * However, there is a non-negative cooling interval n that means between two |
| 22 | + * same tasks, there must be at least n intervals that CPU are doing different |
| 23 | + * tasks or just be idle. |
| 24 | + * |
| 25 | + * You need to return the least number of intervals the CPU will take to finish |
| 26 | + * all the given tasks. |
| 27 | + * |
| 28 | + * |
| 29 | + * |
| 30 | + * Example: |
| 31 | + * |
| 32 | + * |
| 33 | + * Input: tasks = ["A","A","A","B","B","B"], n = 2 |
| 34 | + * Output: 8 |
| 35 | + * Explanation: A -> B -> idle -> A -> B -> idle -> A -> B. |
| 36 | + * |
| 37 | + * |
| 38 | + * |
| 39 | + * |
| 40 | + * Note: |
| 41 | + * |
| 42 | + * |
| 43 | + * The number of tasks is in the range [1, 10000]. |
| 44 | + * The integer n is in the range [0, 100]. |
| 45 | + * |
| 46 | + * |
| 47 | + */ |
| 48 | +class Solution { |
| 49 | + public int leastInterval(char[] tasks, int n) { |
| 50 | + int[] map = new int[26]; |
| 51 | + for (char task : tasks) { |
| 52 | + map[task - 'A']++; |
| 53 | + } |
| 54 | + |
| 55 | + Arrays.sort(map); |
| 56 | + |
| 57 | + int max = map[25] - 1; |
| 58 | + int idle = max * n; |
| 59 | + |
| 60 | + for (int i = 24; i >= 0 && map[i] > 0; i--) { |
| 61 | + idle -= (map[i] > max) ? max : map[i]; |
| 62 | + } |
| 63 | + |
| 64 | + return (idle > 0) ? (tasks.length + idle) : tasks.length; |
| 65 | + } |
| 66 | +} |
| 67 | + |
0 commit comments