LeetCode 1709: Biggest Window Between Visits
Problem Description
Explanation
To solve this problem, we can iterate through the given array and keep track of the maximum distance between the same elements encountered so far. We can achieve this by using a HashMap to store the index of each element as we iterate through the array. When we encounter a repeated element, we calculate the distance between the current index and the previously stored index for that element and update the maximum distance if needed.
- Start with an empty HashMap to store elements and their index.
- Initialize a variable
maxDistance
to 0 to keep track of the maximum distance between same elements. - Iterate through the array.
- If the element is already present in the HashMap, calculate the distance between the current index and the previously stored index for that element.
- Update
maxDistance
if the calculated distance is greater. - Update the index of the element in the HashMap.
- Return the
maxDistance
as the result.
Time Complexity: O(n) where n is the number of elements in the array. Space Complexity: O(n) for the HashMap to store elements and their index.
Solutions
class Solution {
public int maxDistance(int[] nums) {
Map<Integer, Integer> indexMap = new HashMap<>();
int maxDistance = 0;
for (int i = 0; i < nums.length; i++) {
if (indexMap.containsKey(nums[i])) {
maxDistance = Math.max(maxDistance, i - indexMap.get(nums[i]));
}
indexMap.put(nums[i], i);
}
return maxDistance;
}
}
Loading editor...