Sunday, 24 December 2017

Question :
A balanced array is defined to be an array where for every value n in the array, -n also is in the array. For example {-2, 3, 2, -3} is a balanced array. So is {-2, 2, 2, 2}. But {-5, 2, -2} is not because 5 is not in the array.
Write a function named isBalanced that returns 1 if its array argument is a balanced array. Otherwise it returns 0.
If you are programming in Java or C#, the function signature is
int isBalanced (int [ ] a);
If you are programming in C or C++, the function signature is

int isBalanced(int a[ ], int len) where len is the number of elements in the array.
Solution :
public static int isBalanced(int [] a)
        {
            int isBalanced = 1;
            for(int i=0;i<a.Length;i++)
            {
                int isValid = 0;
                for(int j=0;j<a.Length;j++)
                {
                    if(a[i]==-a[j])
                    {
                        isValid = 1;
                        break;
                    }
                }
                if (isValid==0)
                    isBalanced = 0;
            }
            return isBalanced;
        }

1 comment:

Powered by Blogger.

Followers

Translate

Currency Converter

Exchange Rate

Featured post

Interpolation in angular 5

When we want to communicate from component class to template ,we can use interpolation which use the { { expression }} to render the bound...

Popular Posts

My Facebook Page