You are given a string keysPressed
of length n
and an array releaseTimes
where releaseTimes[i]
denotes the time the i-th
key was released. Both the string keysPressed
and the array releaseTimes
are of the same length.
The keypress durations are calculated as follows:
releaseTimes[0]
.releaseTimes[i] - releaseTimes[i-1]
.You need to return the key that had the longest duration. If there is a tie, return the lexicographically largest key.
keysPressed
contain lowercase English letters only?
keysPressed
contains only lowercase English letters.n
of keysPressed
and releaseTimes
?
1 <= n <= 1000
max_duration
to keep track of the maximum duration.result_key
to keep track of the key with the longest duration.max_duration
. If yes, update max_duration
and result_key
.max_duration
but the key is lexicographically larger than result_key
, update result_key
.public class SlowestKey {
public char slowestKey(int[] releaseTimes, String keysPressed) {
int n = releaseTimes.length;
char resultKey = keysPressed.charAt(0);
int maxDuration = releaseTimes[0];
for (int i = 1; i < n; i++) {
int duration = releaseTimes[i] - releaseTimes[i - 1];
if (duration > maxDuration || (duration == maxDuration && keysPressed.charAt(i) > resultKey)) {
maxDuration = duration;
resultKey = keysPressed.charAt(i);
}
}
return resultKey;
}
public static void main(String[] args) {
SlowestKey solution = new SlowestKey();
int[] releaseTimes = {9, 29, 49, 50};
String keysPressed = "cbcd";
System.out.println(solution.slowestKey(releaseTimes, keysPressed)); // Output: 'c'
}
}
n
is the length of keysPressed
or releaseTimes
. We traverse through the list once.maxDuration
, resultKey
).This solution will efficiently find the key with the longest duration while addressing ties using lexicographical order.
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?