Prefix Sum and Sliding Window 09
Given an unsorted array A of size N that contains only non-negative integers, find a continuous sub-array which adds to a given number S.
In case of multiple subarrays, return the subarray which comes first on moving from left to right.
Problem link :- click here
Code
import java.util.Scanner;
// SUBARRAY WITH GIVEN SUM
public class Prefix_sum__Sliding_window_09
{
static int[] subarrayWithGivenSum(int arr[], int S)
{
int m = 0; //size of subarray
int ending_index = -1; //ending index of subarray
int starting_index = -1; //starting index of subarray
int sum = 0; //sum of the subarray
for(int i=0; i<arr.length; i++)
{
sum += arr[i];
m++;
if(sum > S)
{
sum -= arr[i - (m-1)];
m--;
}
if(sum == S)
{
ending_index = i;
break;
}
}
starting_index = ending_index - (m - 1);
int pos[] = {starting_index + 1, ending_index + 1};
return pos;
}
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 the value of k : ");
int k = s.nextInt();
int[] ans = subarrayWithGivenSum(arr, k);
for(int a: ans)
System.out.print(a + "\t");
s.close();
}
}
Comments
Post a Comment