Sunday 24 December 2017

Write a function named largestDifferenceOfEvens which returns the largest difference between even valued elements of its array argument. For example largestDifferenceOfEvens(new int[ ]{-2, 3, 4, 9}) returns 6 = (4 - (-2)). If there are fewer than 2 even numbers in the array, largestDifferenceOfEvens should return -1.

If you are programming in Java or C#, the function signature is
int largestDifferenceOfEvens(int[ ] a)

If you are programming in C or C++, the function signature is
int largestDifferenceOfEvens(int a[ ], int len) where len is the number of elements in the array a.

Examples

a is
then function returns
reason
{1, 3, 5, 9}
-1
because there are no even numbers
{1, 18, 5, 7, 33}
-1
because there is only one even number (18)
{[2, 2, 2, 2]}
0
because 2-2 == 0
{1, 2, 1, 2, 1, 4, 1, 6, 4}
4
because 6 - 2 == 4

   
public static int largestDifferenceOfEvens(int[] a)
        {
            int largestDiff = 0;

            int maxevent = 0, minevent = 0, eventcount = 0;
            
            for (int i = 0; i < a.Length; i++)
            {
                if (a[i] % 2 == 0)
                {
                    if (eventcount == 0)
                    {
                        maxevent = a[i];
                        minevent = a[i];
                    }
                    eventcount++;
                    if (a[i] > maxevent)
                    {
                        maxevent = a[i];
                    }
                    if (a[i] < minevent)
                    {
                        minevent = a[i];
                    }


                }
            }
            largestDiff = maxevent - minevent;

            if (eventcount < 2)
            {
                largestDiff = -1;
            }

            return largestDiff;



        }

0 comments:

Post a 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