Maximum Sum of Sub Array of Size K using Sliding Window Algorithm in c#.
Suppose you are given an array of integers and a size of the sub arrays of the main array. You need to calculate the maximum sum of the sub arrays using Sliding Window algorithm.
Inputs:
int[] arr={2, 3, 7, 8, 1, 3, 5, 6};
int size=3;
Output: 18
Explanation:
Total Sub Array Count will be=arr.Length-k+1=8–3+1=6
Sub Arrays:
{2,3,7} {3,7,8} {7,8,1} {8,1,3} {1,3,5} {3,5,6}
Sums are respectively, 12,18,16,12,9,14
So Maximum Value is : 18
This problem is solved by Fixed Size Sliding Window algorithm. In this algorithm a fixed size of window will move across array like data structure and perform some calculation.
So what we will do,
let's say we are at starting point of the array, i=0 and j=0;
first we will try to get our window , once we got our window we need to maintain it and slide it towards end by increasing value of i and j, our window will be sliding till j reaches the end of the array.So for first time our window will be {2,3,7}, we got our sum and it is 12, notice that, our next window is {3,7,8} which is 18. between these two there is a common part {3,7} whose sum is 10.
So when we will slide, we will take {2} out of sum of {2,3,7}, so sum is now 10 and then we will increase i and j, now i is pointing to 1 {3} and j is pointing to 3 {8} after it is done we will add the arr[3] {8} to the sum, so our new sum will be 18 of {3,7,8} and if it is maximum then we will store, same process will be repeated till j reaches the endpoint of the array.
Code :