The Employee That Worked on the Longest Task
|
|
The function hardestWorker
is trying to find the worker who has the longest continuous working duration. If there are multiple workers with the same longest duration, the function returns the worker with the smallest ID.
Here’s a detailed breakdown of the code:
It initializes
ans
(the ID of the worker with the longest duration so far) to 0,prev
(the ending time of the previous log) to 0, andlongest_duration
(the longest duration so far) to -1.The function then iterates over each log in
logs
. For each log:It calculates the duration of the work log by subtracting
prev
from the ending time of the log.If
longest_duration
is -1 (which means this is the first log being processed) or if the duration is greater than or equal tolongest_duration
, it updatesans
:If the duration is equal to
longest_duration
, it setsans
to the smaller of the current worker’s ID and the previousans
.If the duration is greater than
longest_duration
, it setsans
to the current worker’s ID.
It updates
longest_duration
to the larger of the currentlongest_duration
and the duration.It updates
prev
to the ending time of the current log.
After all logs have been processed, the function returns
ans
, which is the ID of the worker who has the longest continuous working duration.
The time complexity of this function is linear, O(n), as it makes a single pass over the logs. The space complexity is constant, O(1), as it doesn’t use any additional data structures.