The problem requires scheduling tasks with a cool down period 'n' between two
identical
tasks. The key is to
maximize efficiency by
minimizing idle time.
We first
calculate the
maximum frequency of
any task and how many tasks
share this frequency. The
total intervals required are determined by the formula
(mxFreq - 1) * n + mxFreq + cnt - 1,
where
mxFreq is the
maximum frequency and
cnt is the count of tasks
with that frequency. If the total number of tasks is greater than the calculated intervals, we
return the total number of tasks.
class Solution { public int leastInterval(char[] tasks, int n) { int noOfTasks = tasks.length; int[] hashMap = new int[26]; int mxFreq = 0; // Freq of the most frequent task int cnt = 0; // No. of tasks having this maximum frequency for(int i=0;i<noOfTasks;i++){ int ch = tasks[i]-'A'; hashMap[ch]++; if(hashMap[ch]==mxFreq){ cnt++; } if(hashMap[ch]>mxFreq){ cnt = 1; mxFreq = hashMap[ch]; } } // Tasks that have the same maximum frequency will be put in the last i.e cnt-1 // (-1 has come because we have already placed one task that have maximum frequency) // No of gaps after putting the most frequent task = mxFreq-1 // Intervals required to place most frequent task = mxFreq int val = (mxFreq-1)*n + mxFreq + cnt-1; // If the number of tasks itself is greater than the calculated minimum, return noOfTasks. return Math.max(noOfTasks, val); } }
The algorithm iterates through the tasks array once, making it linear in time complexity.
The algorithm uses a constant amount of extra space, as the map size is limited to the number of unique tasks.