Tuesday, 29 May 2018

Find index in an array such that sum of left elements is equal to sum of right in Java



Sample Program:-


 public class SampleProgram {  
      public static void main(String[] args) {  
           int ar[] = { 2, 4, 4, 1, 1 };  
           int leftIndex = 0, rightIndex = ar.length - 1;  
           int leftSum = 0, rightSum = 0;  
           while (leftIndex <= rightIndex) {  
                if (leftSum > rightSum)  
                     rightSum = rightSum + ar[rightIndex--];  
                else  
                     leftSum = leftSum + ar[leftIndex++];  
           }  
           if (leftSum == rightSum)  
                System.out.println("Index is:" + (rightIndex + 1));  
           else  
                System.out.println("index Not Found");  
      }  
 }  

Output:-


Index is:2  

Enjoy Coding.

No comments:

Post a Comment