creative codes
//finding An equilibrium index is a position in the array where the sum of elements to the left = sum of elements to the right.
// Online Java Compiler
// Use this editor to write, compile and run your Java code online
class Main {
public static void main(String[] args) {
int[] arr = {3, 4, 8, -9, 20, 6};
int n = arr.length;
int sum=0;
boolean found=false;
for(int i=0; i<n;i++) sum+=arr[i];
int left_sum=0;
for(int i=0;i<n;i++){
int right_sum=sum-left_sum-arr[i];
if(left_sum==right_sum){
found=true;
System.out.print(sum+"-"+left_sum+"(left)"+"-"+arr[i]+"="+right_sum+"(right)");
System.out.println();
System.out.println(left_sum+"(left)"+"="+right_sum+"(right)");
System.out.println("Equilibrium at index " + i);
break;
}
left_sum+=arr[i];
}
if(!found) System.out.print("no");
}
}
Comments
Post a Comment