Problem 136
Task Scheduler
Medium · 20 pts · Array, Greedy, Heap, Counting
Problem
A CPU must run a list of tasks, each labelled with an uppercase letter. In each time unit it either runs one task or stays idle. Two runs of the same task must be separated by at least K other time units (other tasks or idle slots). Tasks can be run in any order. Find the minimum number of time units needed to run all the tasks. The most frequent task decides the structure. If it appears f times, it needs (f - 1) gaps of length K between its runs, giving (f - 1) × (K + 1) units plus one unit for each task that also appears f times. The answer is the maximum of that number and the total number of tasks.
Input
First line: integers N and K. Second line: N task letters separated by spaces.
Output
Print the minimum number of time units.
Constraints
1 <= N <= 10000; 0 <= K <= 100
Example input
6 2 A A A B B B
Example output
8
Explanation
Tasks A A A B B B with K = 2 can run as A B idle A B idle A B. Each A is 3 units after the previous A, and likewise for B. That takes 8 time units, and no shorter schedule exists.