![]() |
VOOZH | about |
Given an array arr[] and an integer K, the task is to calculate the sum of all subarrays of size K.
Examples:
Input: arr[] = {1, 2, 3, 4, 5, 6}, K = 3
Output: 6 9 12 15
Explanation:
All subarrays of size k and their sum:
Subarray 1: {1, 2, 3} = 1 + 2 + 3 = 6
Subarray 2: {2, 3, 4} = 2 + 3 + 4 = 9
Subarray 3: {3, 4, 5} = 3 + 4 + 5 = 12
Subarray 4: {4, 5, 6} = 4 + 5 + 6 = 15Input: arr[] = {1, -2, 3, -4, 5, 6}, K = 2
Output: -1, 1, -1, 1, 11
Explanation:
All subarrays of size K and their sum:
Subarray 1: {1, -2} = 1 - 2 = -1
Subarray 2: {-2, 3} = -2 + 3 = -1
Subarray 3: {3, 4} = 3 - 4 = -1
Subarray 4: {-4, 5} = -4 + 5 = 1
Subarray 5: {5, 6} = 5 + 6 = 11
Naive Approach: The naive approach will be to generate all subarrays of size K and find the sum of each subarray using iteration.
Below is the implementation of the above approach:
6 9 12 15
Performance Analysis:
The idea is to use the sliding window approach to find the sum of all possible subarrays in the array.
// Adding the element which // adds into the new window sum = sum + arr[j] // Subtracting the element which // pops out from the window sum = sum - arr[j-k] where sum is the variable to store the result arr is the given array j is the loop variable in range [K, N]
Below is the implementation of the above approach:
6 9 12 15
Performance Analysis:
Related Topic: Subarrays, Subsequences, and Subsets in Array