Max Sum Subarray of size K in java

Max Sum Subarray of size K

Given an array of integers Arr of size N and a number K. Return the maximum sum of a subarray of size K

Input

First line contains 2 integers N and K Second line contains N integers denoting elements of array

Output

Print maximum sum subarray of size K

Constraints:

1 <= N <= 1000000 1 <= K <= N -10000 <= Arr[i] <= 10000

Sample Input:

4 2
100 200 300 400

Sample Output:

700

Solution:–

import java.util.*;
import java.lang.*;
import java.io.*;

public class Main
{
	public static void main (String[] args) throws java.lang.Exception
	{
		//your code here
      Scanner sc=new Scanner(System.in);
      int n=sc.nextInt();
      int k=sc.nextInt();
      int[] nums=new int[n];
      int ans=Integer.MIN_VALUE;

      for(int i=0; i<n; i++)
      {
        nums[i]=sc.nextInt();
      }

      for(int i=0; i<n; i++)
      {
        int count=0;
        int sum=0;
        
        for(int j=i; j<n; j++)
        {
          sum+=nums[j];
          count++;
          
          if(k==count)
          {
          ans=Math.max(ans, sum);
          break;
          }
        }
      }
      System.out.println(ans);
	}
}

Add a Comment

Your email address will not be published. Required fields are marked *