Sliding Window is a technique to reduce time complexity for problems involving subarrays or substrings. Instead of nested loops, we βslideβ a window across the input.
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
if (i >= k - 1) {
max = Math.max(max, sum);
sum -= nums[i - k + 1];
}
}
int left = 0;
for (int right = 0; right < s.length(); right++) {
// expand window by including s.charAt(right)
while (window is invalid) {
// shrink window from left
left++;
}
if (window is valid) {
// update result
}
}
int maxSum = 0, windowSum = 0;
for (int i = 0; i < nums.length; i++) {
windowSum += nums[i];
if (i >= k - 1) {
maxSum = Math.max(maxSum, windowSum);
windowSum -= nums[i - k + 1];
}
}