Social Icons

Wednesday, April 21, 2010

canBalance:Solutions for Javabat:11



Given a non-empty array, return true if there is a place to split the array so that the sum of the numbers on one side is equal to the sum of the numbers on the other side.

canBalance({1, 1, 1, 2, 1}) → true
canBalance({2, 1, 1, 2, 1}) → false
canBalance({10, 10}) → true

Source

Possible solution is to make a pass on each element and calculate the sum of elements of to it’s right side and left side .

public boolean canBalance(int[] nums) {
  int sumleft=0,sumaright=0;
  
  for(int i=0 ; i<nums.length;i++ , sumbfor=0 , sumaftr=0){
     
     for(int j=0 ; j<i ; j++)
         sumleft+=nums[j];
     
     for(int k=i; k<nums.length;k++)
         sumright+=nums[k];
     
     if(sumleft==sumright)
       return true;
  }
  
  return false;
}
 
 
 
 
Blogger Templates http://slots.to/