-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSlowestKey.java
41 lines (39 loc) · 1.41 KB
/
SlowestKey.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package leetcode;
/**
* Created at : 07/09/21
* <p>
* <a href=https://leetcode.com/problems/slowest-key/>1629. Slowest Key</a>
*
* @author Himanshu Shekhar
*/
public class SlowestKey {
/**
* <p>Time Complexity: O(n)
* <br>Space Complexity: O(1)
*
* @return key pressed for longest duration
*/
public char slowestKey(int[] releaseTimes, String keysPressed) {
int n = releaseTimes.length;
// initially, consider 1st key is pressed for longest duration
int longestDuration = releaseTimes[0];
char keyPressed = keysPressed.charAt(0);
// search for other keys in the array
for (int i = 1; i < n; i++) {
// check if current duration is greater than my previous duration
// we'll update our previous duration and key pressed as well
if (longestDuration < releaseTimes[i] - releaseTimes[i - 1]) {
longestDuration = releaseTimes[i] - releaseTimes[i - 1];
keyPressed = keysPressed.charAt(i);
}
// if duration is same then we need to take the character
// which is lexicographically largest
else if (longestDuration == releaseTimes[i] - releaseTimes[i - 1]) {
if (keyPressed < keysPressed.charAt(i)) {
keyPressed = keysPressed.charAt(i);
}
}
}
return keyPressed;
}
}