Task Scheduler in Java: Explanation & Practice

Minimum time to complete all tasks with cooldown

Problem summary

Given tasks and cooldown n, find minimum time to complete all tasks. Same tasks must have at least n intervals between them.

Starter code

public class Main {
    public static void main(String[] args) {
        char[] tasks = {'A','A','A','B','B','B'};
        int n = 2;
        
        // Greedy: schedule most frequent task first
        // Calculate idle slots needed
        // Print: Time: 8
    }
}

Expected output and test cases

  • A B idle A B idle A B
    Time: 8
  • n=0 → no cooldown needed
    Time: 6
  • A A A B B B, n=3
    Time: 16

Hints

  1. Count frequency of each task
  2. Most frequent task determines minimum slots needed
  3. Formula: (maxFreq - 1) * (n + 1) + numTasksWithMaxFreq
  4. Answer is max of this formula and total tasks

Related Data Structures & Algorithms exercises

Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler