Window Sliding Technique-Solution

Aditya Raj Singh
1 min readJun 25, 2021

PROBLEM: Given an array of integers of size n, calculate the maximum sum of k consecutive elements in the array.

Input  : arr[] = {100, 200, 300, 400}
k = 2
Output : 700

Input : arr[] = {1, 4, 2, 10, 23, 3, 1, 0, 20}
k = 4
Output : 39
We get maximum sum by adding subarray {4, 2, 10, 23}
of size 4.

SOLUTION:

import java.util.*;
public class Window {
static int maxSum(int arr[], int n, int k)
{
int max_sum = Integer.MIN_VALUE;
for (int i = 0; i < n — k + 1; i++) {
int current_sum = 0;
for (int j = 0; j < k; j++)
current_sum = current_sum + arr[i + j];
max_sum = Math.max(current_sum, max_sum);
}
return max_sum;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print(“\nEnter Array Size:”);
int n = sc.nextInt();
int[] arr = new int[n];
System.out.print(“\nEnter the array:”);
for(int i=0;i<n;i++){
arr[i] = sc.nextInt();
}
System.out.print(“\nEnter the window size:”);
int k = sc.nextInt();
System.out.println(maxSum(arr, n, k));
}
}

RESULT

Input:Enter Array Size:9Enter the array:1
4
2
10
2
3
1
0
20
Enter the window size:4Output24

--

--