Sliding Window

Here’s an example implementation of Sliding Window:

Python

def maxSum(arr, k):
	# length of the array
	n = len(arr)

	# length of array must be greater
        # window size
	if n < k:
		print("Invalid")
		return -1

	# sum of first k elements
	window_sum = sum(arr[:k])
	max_sum = window_sum

	# remove the  first element of previous
	# window and add the last element of
	# the current window to calculate the 
    # the sums of remaining windows by
	for i in range(n - k):
		window_sum = window_sum - arr[i] + arr[i + k]
		max_sum = max(window_sum, max_sum)

	return max_sum


arr = [16, 12, 9, 19, 11, 8]
k = 3
print(maxSum(arr, k))

C++

#include <iostream>
#include <algorithm>  // for std::max

// Returns maximum sum in a subarray of size k.
int maxSum(int arr[], int n, int k) {
    // n must be greater
    if (n < k) {
        std::cout << "Invalid";
        return -1;
    }

    // Sum of first window of size k
    int window_sum = 0;
    for (int i = 0; i < k; i++)
        window_sum += arr[i];

    // Compute sums of remaining windows by
    // removing first element of previous
    // window and adding last element of
    // current window.
    int max_sum = window_sum;
    for (int i = k; i < n; i++) {
        window_sum += (arr[i] - arr[i - k]);
        max_sum = std::max(max_sum, window_sum);
    }
    return max_sum;
}

int main() {
    int n = 6, k = 3;  // Adjusted to match the size of the array
    int arr[] = {16, 12, 9, 19, 11, 8};
    std::cout << maxSum(arr, n, k);
    return 0;
}
Click to view another code.

Python

lst = [1,2,3,4,5,6,7,8] 
def sliding_window(elements, window_size):
    
    if len(elements) <= window_size:
       return elements
    for i in range(len(elements)):
        print(elements[i:i+window_size])

Output

sliding_window(lst, 3)

Output:

[1, 2, 3] 
[2, 3, 4] 
[3, 4, 5] 
[4, 5, 6] 
[5, 6, 7] 
[6, 7, 8] 
[7, 8] 
[8]

Python

# modified code to stop on window size

lst = [1,2,3,4,5,6,7,8] 
def sliding_window(elements, window_size):
    
    if len(elements) <= window_size:
       return elements
    for i in range(len(elements)- window_size + 1):
        print(elements[i:i+window_size])

Output

sliding_window(lst, 3)


Output:

[1, 2, 3] 
[2, 3, 4] 
[3, 4, 5] 
[4, 5, 6] 
[5, 6, 7] 
[6, 7, 8]

Python

# sliding window to calculate substrings

s = "eidbaooo"
def sliding_window(elements, window_size):
    
    if len(elements) <= window_size:
       return elements
    for i in range(len(elements)- window_size + 1):
        print(elements[i:i+window_size])

Output

sliding_window(s, 2)


Output:

ei 
id 
db 
ba 
ao 
oo 
oo


References:

Previous
Next