Sponsored
Sponsored
This approach involves iterating through both releaseTimes
and keysPressed
to calculate the duration of each keypress. We'll track the maximum duration found so far and update our result each time we find a keypress with a longer duration. If two keypresses have the same duration, we choose the lexicographically larger key.
Time Complexity: O(n), where n is the length of the releaseTimes array. We iterate through the list once.
Space Complexity: O(1), as we only use constant extra space for variables.
1#include <stdio.h>
2#include <string.h>
3
4char slowestKey(int* releaseTimes, int releaseTimesSize, char* keysPressed) {
5 int maxDuration = releaseTimes[0];
6 char result = keysPressed[0];
7 for (int i = 1; i < releaseTimesSize; ++i) {
8 int duration = releaseTimes[i] - releaseTimes[i - 1];
9 if (duration > maxDuration || (duration == maxDuration && keysPressed[i] > result)) {
10 maxDuration = duration;
11 result = keysPressed[i];
12 }
13 }
14 return result;
15}
16
17int main() {
18 int releaseTimes[] = {12, 23, 36, 46, 62};
19 char keysPressed[] = "spuda";
20 printf("%c\n", slowestKey(releaseTimes, 5, keysPressed));
21 return 0;
22}
We initialize the maximum duration with the duration of the first keypress and iteratively check each subsequent duration. The key with the longest duration is tracked and returned. The code checks if the current duration is greater than the maximum duration found so far or if the key is lexicographically larger when durations are equal.
In this approach, we create a temporary array to store the duration of each key press. We then iterate over this array to find the maximum duration. This solution separates the concerns of calculation and comparison for more clarity.
Time Complexity: O(n)
Space Complexity: O(n) due to additional array usage.
1function
In this JavaScript implementation, a temporary durations array helps facilitate the separation of computation and decision processes.