This is an algorithmic problem I came across during a coding interview, and I couldn't find a solution faster than an O(n^2)
one.
The original problem seems to be a little lengthy, so I rephrase the problem into a round-robin process scheduling one one, which hopefully is more comprehensible.
Given n
processes which are all initially in ready state, and an array T
of size n
, where T[i]
is the time to run process i
.
We run the process in the order from process 0
to process n-1
, and each time we run the selected process exactly 1
unit of time. If a process is finished, we skip it. We continue running the processes until all processes are finished.
Please give an efficient algorithm that outputs the total turnaround time of all processes. (The turnaround time of a process is the time it takes from being ready to being finished.)
Constraints:
1 <= n <= 10**5
1 <= T[i] <= 10**4
For example, T = [3, 1, 2]
,
we would have T = [2, 1, 2]
(run process[0]
), then T = [2, 0, 2]
(run process[1]
), then T = [2, 0 , 1]
(run process[2]
) and so on.
So It takes 6
unit of times for process[0]
to complete, and 2
unit of time for process[1]
to complete, and 5
unit of time for process[2]
to complete. And we should output 6+2+5=13
.
My idea is that, for each process[i]
we have to wait
process[0]
toprocess[i-1]
T[i]
process[i+1]
toprocess[n-1]
For each process[j]
in 1., process[i]
has to wait min(T[j], T[i])
unit of time.
For each process[j]
in 3., process[i]
has to wait min(T[i]-1, T[j])
unit of time.
So each process[i]
has turnaround time T[i] + sum_(j=0~(i-1))(min(T[j], T[i])) + sum_(j=(i+1)~(n-1)(min(T[j], T[i]-1))
, and the answer is just summing up all turnaround time of process[i]
.
As we can see from the formula, it takes O(n)
time to compute each turnaround time, and thus total O(n^2)
time to solve the problem.
I was wondering if there is any way to optimize the solution to O(n) time. (Maybe by prefix sum or dynamic programming, but i am not sure.)
Thanks for the comments!