Problem Description
Explanation:
To solve this problem, we need to iterate through the keys pressed and calculate the duration of each keypress. We will keep track of the longest duration and the lexicographically largest key with that duration. We will update these values as we iterate through the keys. Finally, we return the lexicographically largest key with the longest duration.
- Initialize variables
maxDuration
as 0 andmaxKey
as the first key pressed. - Iterate through the keys pressed:
- Calculate the duration of the current keypress.
- If the current keypress duration is greater than
maxDuration
, updatemaxDuration
andmaxKey
. - If the current keypress duration is equal to
maxDuration
, updatemaxKey
with the lexicographically largest key.
- Return the
maxKey
.
Time Complexity:
The time complexity of this solution is O(n) where n is the number of keypresses.
Space Complexity:
The space complexity of this solution is O(1) as we are using a constant amount of extra space.
:
Solutions
class Solution {
public char slowestKey(int[] releaseTimes, String keysPressed) {
int n = releaseTimes.length;
int maxDuration = releaseTimes[0];
char maxKey = keysPressed.charAt(0);
for (int i = 1; i < n; i++) {
int duration = releaseTimes[i] - releaseTimes[i - 1];
if (duration > maxDuration || (duration == maxDuration && keysPressed.charAt(i) > maxKey)) {
maxDuration = duration;
maxKey = keysPressed.charAt(i);
}
}
return maxKey;
}
}
Loading editor...