Sunday, 24 December 2017

Question :

An Sub array is defined to be an array in which each element is greater than sum of all elements after that. See examples below:

{13, 6, 3, 2} is a Sub array. Note that 13 > 2 + 3 + 6, 6 > 3 + 2, 3 > 2.

{11, 5, 3, 2} is a NOT a Sub array. Note that 5 is not greater than 3 + 2.


Write a function named isSub that returns 1 if its array argument is a Sub array, otherwise it returns 0.

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

If you are programming in C or C++, the function signature is:

   int isSub (int a[ ], int len) where len is the number of elements in the array.

Solution :
public int isSub(int [] a)
        {   
            int rtnVal = 1, sum = 0;
            for(int i=a.Length-1;i>0;i--)
            {
                sum += a[i];
                if(sum>=a[i-1])
                {
                    rtnVal = 0;
                        break;
                }
            }
            return rtnVal;
        }

1 comment:

  1. static int isSub(int[] a) {
    for(int i=0; i<a.length; i++){
    int sum = 0;
    for(int j=i+1; j<a.length; j++)
    sum+=a[j];
    if(a[i]<sum)
    return 0;
    }
    return 1;
    }

    ReplyDelete

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