from typing import List
class Solution:
def biggestWindow(self, visits: List[int]) -> int:
if not visits or len(visits) == 1:
return 0
max_gap = 0
for i in range(1, len(visits)):
gap = visits[i] - visits[i-1]
max_gap = max(max_gap, gap)
return max_gap
#include <vector>
#include <algorithm>
class Solution {
public:
int biggestWindow(std::vector<int>& visits) {
if (visits.size() <= 1) return 0;
int max_gap = 0;
for (size_t i = 1; i < visits.size(); ++i) {
int gap = visits[i] - visits[i-1];
max_gap = std::max(max_gap, gap);
}
return max_gap;
}
};
class Solution {
public int biggestWindow(int[] visits) {
if (visits == null || visits.length <= 1) return 0;
int maxGap = 0;
for (int i = 1; i < visits.length; i++) {
int gap = visits[i] - visits[i-1];
if (gap > maxGap) {
maxGap = gap;
}
}
return maxGap;
}
}
/**
* @param {number[]} visits
* @return {number}
*/
var biggestWindow = function(visits) {
if (!visits || visits.length <= 1) return 0;
let maxGap = 0;
for (let i = 1; i < visits.length; i++) {
let gap = visits[i] - visits[i - 1];
if (gap > maxGap) {
maxGap = gap;
}
}
return maxGap;
};
Given an array visits
representing the times (as integers) at which a user visited a website, your task is to find the largest time window (gap) between two consecutive visits. The array visits
is sorted in ascending order and contains at least one integer. The result should be the maximum difference between any two consecutive elements in visits
. If there is only one visit, return 0.
visits
is unique and sorted in ascending order.The problem is essentially about finding the largest gap between two consecutive numbers in a sorted list. The brute-force approach would be to check all possible pairs, but since the array is sorted and only consecutive pairs matter, we can optimize by just checking each adjacent pair.
This is similar to looking at a timeline and asking: "Where is the longest period without a visit?" Since the visits are sorted, the biggest gap must be between two consecutive entries.
visits
array has less than two elements. If so, return 0, as there are no consecutive pairs to compare.
max_gap
) to keep track of the largest gap found so far.
i
, compute the gap as visits[i] - visits[i-1]
.
max_gap
, update max_gap
.
max_gap
.
This approach is efficient because we only need to look at each pair once, and we store only the maximum gap found.
Suppose visits = [2, 5, 9, 15]
.
The gaps are 3, 4, and 6. The biggest gap is 6 (between 9 and 15). Thus, the function should return 6.
visits
.
max_gap
variable), so space complexity is O(1).
The key insight is that since the visits
array is sorted, the biggest window between visits will always be between two consecutive elements. By iterating once through the array and checking each adjacent pair, we can efficiently find the answer in linear time. This makes the solution both simple and elegant.