Prefix Sum and Sliding Window 07
Given an array of integers Arr of size N and a number K. Return the maximum sum of a subarray of size K.
Problem link :- click here
Code
import java.util.Scanner;
// MAX SUM SUBARRAY OF SIZE K
public class Prefix_sum__Sliding_window_07
{
static int maxSumOfSubarrayOfSizeK(int arr[], int k)
{
if(k > arr.length)
return -1;
// SLIDING WINDOW
/*
arr = {100, 200, 300, 100} k = 2
step1: - add the values of first k elements to `sum` and update `maxSum`.
step2: - until last element of the `arr` ( i=k to i=n)
i) subtract the value of leftmost element which is not yet subtracted
from `sum`.
ii) add the value of the present element in the iteration. i.e., `i`.
iii) update the `maxSum`.
sum = arr[0] + arr[2]
sum = 100 + 200
= 300
maxSum = 300
sum = sum - arr[0] subtract
= 300 - 100
= 200
sum = sum + arr[2] add
= 200 + 300
= 500
maxSum = 500
sum = sum - arr[1] subtract
= 500 - 200
= 300
sum = sum + arr[3] add
= 300 + 100
= 400
maxSum = 500
*/
int maxSum = 0;
int sum = 0;
//step1: -
for(int i=0; i<k; i++)
sum += arr[i];
if(sum > maxSum)
maxSum = sum;
//step2: -
for(int i=k; i<arr.length; i++)
{
sum -= arr[i-k];
sum += arr[i];
if(sum > maxSum)
maxSum = sum;
}
return maxSum;
}
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
// Taking size of array and array as input from the user
System.out.print("Enter the size of the array : ");
int n = s.nextInt();
int[] arr = new int[n];
System.out.println("Enter the array elements : ");
for(int i=0; i<n; i++)
arr[i] = s.nextInt();
System.out.print("Enter the value of k : ");
int k = s.nextInt();
int maxSum = maxSumOfSubarrayOfSizeK(arr, k);
System.out.println(maxSum);
s.close();
}
}
Comments
Post a Comment