Leetcode 2432. The Employee That Worked on the Longest Task
You are given a 0-indexed integer array logs
, where logs[i] = [id_i, time_i] indicates that the i-th
employee started the i-th
task at time_i
.
The task with logs[i]
was completed at time_i + d_i
, and no later tasks start earlier than this completion time.
Your goal is to find the id of the employee that worked on the task that had the longest duration. If there is a tie, return the smallest id.
Example:
Input: n = 3, logs = [[0,2],[1,3],[2,7]]
Output: 2
n
and logs
?
n
can be between 1 and 10^5.logs
is equal to the number of tasks done and can be up to 10^5.#include <vector>
#include <algorithm>
#include <climits>
int hardestWorker(int n, std::vector<std::vector<int>>& logs) {
int maxDuration = INT_MIN;
int employeeId = INT_MAX;
int prevTime = 0;
for (const auto& log : logs) {
int id = log[0];
int startTime = log[1];
// Compute duration of the current task
int taskDuration = startTime - prevTime;
// Check if this duration is longer than the current max duration
if (taskDuration > maxDuration ||
(taskDuration == maxDuration && id < employeeId)) {
maxDuration = taskDuration;
employeeId = id;
}
// Update previous task complete time to current task start time
prevTime = startTime;
}
return employeeId;
}
This solution ensures efficient handling of potentially large input sizes due to its linear time complexity.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?