3632. Button With Longest Push Time¶
3632. Button with Longest Push Time
Easy
You are given a 2D array events which represents a sequence of events where a child pushes a series of buttons on a keyboard.
Each events[i] = [indexi, timei] indicates that the button at index indexi was pressed at time timei.
- The array is sorted in increasing order of
time. - The time taken to press a button is the difference in time between consecutive button presses. The time for the first button is simply the time at which it was pressed.
Return the index of the button that took the longest time to push. If multiple buttons have the same longest time, return the button with the smallest index.
Example 1:
Input: events = [[1,2],[2,5],[3,9],[1,15]]
Output: 1
Explanation:
- Button with index 1 is pressed at time 2.
- Button with index 2 is pressed at time 5, so it took
5 - 2 = 3units of time. - Button with index 3 is pressed at time 9, so it took
9 - 5 = 4units of time. - Button with index 1 is pressed again at time 15, so it took
15 - 9 = 6units of time.
Example 2:
Input: events = [[10,5],[1,7]]
Output: 10
Explanation:
- Button with index 10 is pressed at time 5.
- Button with index 1 is pressed at time 7, so it took
7 - 5 = 2units of time.
Constraints:
1 <= events.length <= 1000events[i] == [indexi, timei]1 <= indexi, timei <= 105- The input is generated such that
eventsis sorted in increasing order oftimei.
Solution¶
class Solution {
public int buttonWithLongestTime(int[][] events) {
int n = events.length;
int maxi_diff = 0, ans = n;
for (int i = 0; i < n - 1; i++) {
int current = events[i][1];
int next = events[i + 1][1];
if (next - current > maxi_diff) {
maxi_diff = next - current;
ans = events[i + 1][0];
ans = Math.min(ans, events[i + 1][0]);
}
else if (next - current == maxi_diff) ans = Math.min(ans, events[i + 1][0]);
}
int current = 0;
int next = events[0][1];
if (next - current > maxi_diff) {
maxi_diff = next - current;
ans = events[0][0];
}
else if (next - current == maxi_diff) ans = Math.min(ans, events[0][0]);
return ans;
}
}
Complexity Analysis¶
- Time Complexity: O(?)
- Space Complexity: O(?)
Explanation¶
[Add detailed explanation here]