Skip to content

2432. The Employee That Worked on the Longest Task 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  int hardestWorker(int n, vector<vector<int>>& logs) {
    int ans = logs[0][0];
    int maxWorkingTime = logs[0][1];

    for (int i = 1; i < logs.size(); ++i) {
      const int id = logs[i][0];
      const int workingTime = logs[i][1] - logs[i - 1][1];
      if (workingTime > maxWorkingTime) {
        ans = id;
        maxWorkingTime = workingTime;
      } else if (workingTime == maxWorkingTime) {
        ans = min(ans, id);
      }
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public int hardestWorker(int n, int[][] logs) {
    int ans = logs[0][0];
    int maxWorkingTime = logs[0][1];

    for (int i = 1; i < logs.length; ++i) {
      final int id = logs[i][0];
      final int workingTime = logs[i][1] - logs[i - 1][1];
      if (workingTime > maxWorkingTime) {
        ans = id;
        maxWorkingTime = workingTime;
      } else if (workingTime == maxWorkingTime) {
        ans = Math.min(ans, id);
      }
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def hardestWorker(self, n: int, logs: list[list[int]]) -> int:
    ans = logs[0][0]
    maxWorkingTime = logs[0][1]

    for (_, prevLeaveTime), (id, leaveTime) in zip(logs, logs[1:]):
      workingTime = leaveTime - prevLeaveTime
      if workingTime > maxWorkingTime:
        ans = id
        maxWorkingTime = workingTime
      elif workingTime == maxWorkingTime:
        ans = min(ans, id)

    return ans