Prefix Sum and Sliding Window 03

Given an array containing N integers and an integer K, Your task is to find the length of the longest Sub-Array with the sum of the elements equal to the given value k.

Problem link :- click here


Code



import java.util.Scanner;

// LONGEST SUBARRAY WITH SUM K

public class Prefix_sum__Sliding_window_03
{
	
	//	Sliding window technique
	static int sizeOfSubarrayWithSumK(int[] arr, int k)
	{
		int max_m = 0;
		int m = 0;	// 	length of subarray
		int sum = 0;
		
		for(int i=0; i<arr.length; i++)
		{
			sum += arr[i];
			m++;
			
			if(sum == k)
				max_m = m;
			else if(sum > k)
			{
				//	deleting the first element of the sub-array
				sum -= arr[i-(m-1)];
				m--;
			}
		}
		
		return max_m;
	}

	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 sum value : ");
		int k = s.nextInt();
		
		int max_m = sizeOfSubarrayWithSumK(arr, k);
		System.out.println(max_m);
	}

}



Comments