|
| 1 | +/** |
| 2 | + * 1629. Slowest Key |
| 3 | + * https://leetcode.com/problems/slowest-key/ |
| 4 | + * Difficulty: Easy |
| 5 | + * |
| 6 | + * A newly designed keypad was tested, where a tester pressed a sequence of n keys, one at a time. |
| 7 | + * |
| 8 | + * You are given a string keysPressed of length n, where keysPressed[i] was the ith key pressed in |
| 9 | + * the testing sequence, and a sorted list releaseTimes, where releaseTimes[i] was the time the |
| 10 | + * ith key was released. Both arrays are 0-indexed. The 0th key was pressed at the time 0, and |
| 11 | + * every subsequent key was pressed at the exact time the previous key was released. |
| 12 | + * |
| 13 | + * The tester wants to know the key of the keypress that had the longest duration. The ith keypress |
| 14 | + * had a duration of releaseTimes[i] - releaseTimes[i - 1], and the 0th keypress had a duration of |
| 15 | + * releaseTimes[0]. |
| 16 | + * |
| 17 | + * Note that the same key could have been pressed multiple times during the test, and these multiple |
| 18 | + * presses of the same key may not have had the same duration. |
| 19 | + * |
| 20 | + * Return the key of the keypress that had the longest duration. If there are multiple such |
| 21 | + * keypresses, return the lexicographically largest key of the keypresses. |
| 22 | + */ |
| 23 | + |
| 24 | +/** |
| 25 | + * @param {number[]} releaseTimes |
| 26 | + * @param {string} keysPressed |
| 27 | + * @return {character} |
| 28 | + */ |
| 29 | +var slowestKey = function(releaseTimes, keysPressed) { |
| 30 | + let maxDuration = releaseTimes[0]; |
| 31 | + let result = keysPressed[0]; |
| 32 | + |
| 33 | + for (let i = 1; i < releaseTimes.length; i++) { |
| 34 | + const duration = releaseTimes[i] - releaseTimes[i - 1]; |
| 35 | + if (duration > maxDuration || (duration === maxDuration && keysPressed[i] > result)) { |
| 36 | + maxDuration = duration; |
| 37 | + result = keysPressed[i]; |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + return result; |
| 42 | +}; |
0 commit comments