Sliding window is a really popular technique used to solve complex problems related to Strings and Arrays. It generally reduces the time complexity of a solution from O(N2) to O(N).
The idea is to make a window of certain length that will satisfy the problem constraints. Generally, the window is represented with 2 pointers --- Left and Right --- that points to a specific index in the Array or a specific character in the case of a String.
The window down scales based on the problem and it continues to do so until the window either reaches the end of the Array / String or it finds the answer, in which case it returns.
Example for better Understanding
Input : arr[] = {8, 5, 10, 7, 9, 4, 15, 12, 90, 13}, k = 3
Output : 117
We get maximum sum by adding subarray {15, 12, 90} of size 3.
Solution
class Main {
// Returns maximum sum in
// a subarray of size k.
static int maxSum(int arr[], int n, int k)
{
// n must be greater
if (n < k) {
System.out.println("Invalid");
return -1;
}
// Compute sum of first window of size k
int max_sum = 0;
for (int i = 0; i < k; i++)
max_sum += arr[i];
// Compute sums of remaining windows by
// removing first element of previous
// window and adding last element of
// current window.
int window_sum = max_sum;
for (int i = k; i < n; i++) {
window_sum += arr[i] - arr[i - k];
max_sum = Math.max(max_sum, window_sum);
}
return max_sum;
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 1, 4, 2, 10, 2, 3, 1, 0, 20 };
int k = 4;
int n = arr.length;
System.out.println(maxSum(arr, n, k));
}
}
Practice on these
Thank you for reading till the end, if you like this blog then please
share it with your friends so that they can also learn and grow with you π.