Prefix Sum and Sliding Window 01
Given an array A of n positive numbers. The task is to find the first Equilibrium Point in the array. Equilibrium Point in an array is a position such that the sum of elements before it is equal to the sum of elements after it.
Problem link :- click here
Code
// EQUILIBRIUM POINT
import java.util.Scanner;
public class Prefix_sum__Sliding_window_01
{
static int equilibriumPoint(int[] arr, int n)
{
// Calculating prefix sum array(psa)
int[] psa = new int[n];
psa[0] = arr[0];
for(int i=1; i<n; i++)
psa[i] = psa[i-1] + arr[i];
/*
NOTE: -
if n==1 then the only element in the array is the equilibrium point
if n==2 then there will not be any equilibrium point
To find the equilibrium point steps are: -
1) We have to iterate through each element starting from index 1, `ref`
2) Then we have to compare the sum of elements to the left <---- of `ref`
and the sum of elements to the right ----> of `ref`
3) sum of elements to left of `ref` = psa[ref-1]
4) sum of elements to right of `ref` = psa[n-1] - psa[ref]
Since the given array contains only positive integers, there can be only 1 equilibrium point.
*/
if(n==1)
return 1;
if(n==2)
return -1;
for(int ref=1; ref<n; ref++)
{
int leftSum = psa[ref-1];
int rightSum = psa[n-1] - psa[ref];
if(leftSum == rightSum)
{
return (ref+1); //ref+1 for 1 index
}
}
return -1;
}
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();
int index = equilibriumPoint(arr, n);
if(index == -1)
System.out.println("\nEquilibrium Point doesn't exists");
else
System.out.println("\nEquilibrium Point is : " + index);
}
}
Comments
Post a Comment