Examples
Example 1:
Input: releaseTimes = [9,29,49,50], keysPressed = "cbcd"
Output: "c"
Explanation: The keypresses were as follows:
Keypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9).
Keypress for 'b' had a duration of 29 - 9 = 20 (pressed at time 9 right after the release of the previous character and released at time 29).
Keypress for 'c' had a duration of 49 - 29 = 20 (pressed at time 29 right after the release of the previous character and released at time 49).
Keypress for 'd' had a duration of 50 - 49 = 1 (pressed at time 49 right after the release of the previous character and released at time 50).
The longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20.
'c' is lexicographically larger than 'b', so the answer is 'c'.
Example 2:
Input: releaseTimes = [12,23,36,46,62], keysPressed = "spuda"
Output: "a"
Explanation: The keypresses were as follows:
Keypress for 's' had a duration of 12.
Keypress for 'p' had a duration of 23 - 12 = 11.
Keypress for 'u' had a duration of 36 - 23 = 13.
Keypress for 'd' had a duration of 46 - 36 = 10.
Keypress for 'a' had a duration of 62 - 46 = 16.
The longest of these was the keypress for 'a' with duration 16.
Code
class Solution {
public:
char slowestKey(vector<int>& releaseTimes, string keysPressed) {
vector<int> diff_relt(releaseTimes.size(), 0);
diff_relt[0] = releaseTimes[0];
for (int i = 1; i < releaseTimes.size(); i++)
diff_relt[i] = releaseTimes[i] - releaseTimes[i-1];
vector<int> max_indices;
int max_times = 0;
for (int i = 0; i < diff_relt.size(); i++) {
if (diff_relt[i] > max_times) {
max_times = diff_relt[i];
max_indices.clear();
max_indices.push_back(i);
continue;
}
if (diff_relt[i] == max_times) {
max_indices.push_back(i);
}
}
char lexmax = 0;
for (int i = 0; i < max_indices.size(); i++) {
if (lexmax < keysPressed[max_indices[i]])
lexmax = keysPressed[max_indices[i]];
}
return lexmax;
}
}
Logic
There's three main components to this:
- Find the differences between the
releaseTimesand store them. - Find the max difference (which is the slowest key) and store its index. There may be multiple of them, the problem requires us to store all of them.
- Iterate over all of them and find the which is lexographically greatest
keyPressedelement
Keep in mind that:
- The first element's release time is not calculated.
- There can be multiple max differences that are equal in value.