- codewithshiva

Latest

Search Bar

Tuesday, July 6, 2021

 Equilibrium Element

Description

Given an array A of N positive numbers. The task is to find the position where equilibrium first occurs in the array. Equilibrium position in an array is a position such that the sum of elements before it is equal to the sum of elements after it.

Input

Input Format

First line contains an integer N denoting the size of the array.

Then in the next line are N space separated values of the array A.

N <= 1000

Ai <= 10000

Output

In a new line print the position at which the elements are at equilibrium if no equilibrium point exists print -1.


Sample Input 1 

5
3 3 5 5 1

Sample Output 1

3


import java.util.Scanner;

public class Main {


    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        int lenof_arr =sc.nextInt();

        int[] array = new int[lenof_arr];


        int sumAll= 0;

        for (int k = 0;k<lenof_arr;k++){

            array[k] = sc.nextInt();

            sumAll=sumAll+array[k];

        }


        int sumleft = 0;

        int hit = 0;


        for (int k = 1;k<lenof_arr;k++){

            sumleft=sumleft+array[k-1];

            if (sumleft == sumAll-sumleft-array[k]){

                System.out.println(k+1);

                hit = hit+1;

                break;

            }

        }

        if (hit != 1){

            System.out.println(-1);

        }

    }

}


No comments:

Post a Comment