A balanced array
is defined to be an array where for every value n
in the array, -n
also is in the array.
{-2, 3, 2, -3}
is a balanced array.- So is
{-2, 2, 2, 2}
. But{-5, 2, -2}
is not because5
is not in the array.
I wrote the following class BalancedArray
which satisfied above condition.
public class BalancedArray {
public static void main(String args[]) {
System.out.println("The result is: " + isBalanced(new int[]{-2, 3, 2, -3}));
}
public static boolean isBalanced(int[] a){
boolean status = false;
for(int i = 0; i < a.length; i++) {
if(a[i] > 0) {
for(int j = i+1; j < a.length; j++) {
if(a[i] == Math.abs(a[j])) {
status = true;
}
}
} else if(a[i] < 0) {
for(int k = i+1; k < a.length; k++) {
if(Math.abs(a[i]) == a[k]) {
status = true;
}
}
}
System.out.println(status);
if(status) {
status= true;
} else {
status = false;
break;
}
}
return status;
}
}
Is this proper way to check Balanced array
or I am missing some conditions to check in array??
{ 2 , 2 }
will result intrue
– Heslacher Jan 21 at 14:430
– is it self-balancing or does it need another0
to satisfy0==-0
...? – CiaPan Jan 21 at 16:40