206 questions

123 answers

13 comments

141 users

Sapient Technical Interview question Find Balance Point In Array in Java

0 votes
Find Balance Point In Array

Index of array for which left side elements sum is equal to right side elements sum

Example :Given Array {2,7, 4, 5, -3, 8, 9, -1 }  Balance point is index 3

For 3rd index left side elements sum is 13(2+7+4) and right side elements sum is 13 (-3+8+9-1), so Balance point is 3
asked Jun 1 in Programming language by anonymous

1 Answer

0 votes
public class BalancePointInArray {

    public static void main(String[] args) {
        
        int input[]={2,7, 4, 5, -3, 8, 9, -1 };// input Array Balance point here is 3
        
        System.out.println("Balance Point :"+findBalancePoint(input));
    }
    
    public static int findBalancePoint(int[] input)
    {
        int leftSum=input[0];  //get the First element as left Sum
        int rightSum=0;
        for (int i = 0; i < input.length; i++) {
            rightSum+=input[i];  //get the all elements sum as right Sum
        }
        
        for (int i = 0; i < input.length-1; i++) {  // Loop till one less element in array so that we can compare
            
            if(leftSum==rightSum)  // we comparing Balance Point value
                return i;
            
            leftSum+=input[i+1];  // keep +  left sum until Balance point
            rightSum-=input[i];  // keep - right sum until only have Balance Point
        }
        return -1;
    }

}
answered Jun 1 by anonymous
...