By Long Luo

# Intuition

To simulate the CPU operations, there comes $3$ questions:

2. How to maintain the enqueued tasks?

Let’s answer the $3$ questions:

1. We assign the tasks to the CPU by $\textit{enqueueTime}$, so we sort the array first by $\textit{enqueueTime}$. However, we will lose the $\textit{index}$ of the task.

We can parse the task by creating a new class $\texttt{Job}$, whose members are $\textit{id}$, $\textit{enqueueTime}$, $\textit{processTime}$.

1. We put all the tasks assigned to the CPU into a Priority Queue and poll out the task whose $\textit{processTime}$ is the least each time.

2. We can maintain a $\textit{curTime}$ variable, which represents the current time with initial value is $0$.

If the CPU has no tasks to execute, we set the $\textit{curTime}$ to $\textit{enqueueTime}$ of the next task in the array that has not yet been assigned to the CPU.

After this, we put all $\textit{enqueueTime} \le \textit{curTime}$ tasks into the Priority Queue.

We can use an extra array which store the indices of the $\textit{tasks}$, then sorting the array by $\textit{enqueueTime}$.

So we can write more clean code.

## Analysis

• Time Complexity: $O(nlogn)$.
• Space Complexity: $O(n)$.

All suggestions are welcome.
If you have any query or suggestion please comment below.
Please upvote👍 if you like💗 it. Thank you:-)

Explore More Leetcode Solutions. 😉😃💗