Accenture coding question | Number of balls required | june 2021

Problem Statement: Implement the following function

int NumberOfBalls(int arr[],int n);

The function accepts a non-negative integer array 'arr' of size n as its argument. Every kth element in array is the number of balls in kth row of a box. Every kth row of the box  needs (k+1)2 balls, where 0<=k<=(n-1). Implement the function to find number of balls required to complete each row of the box and return the total number of balls required.

Assumption : arr[k]<=(k+1)2

Note:

  1. ·        Return -1 if array is null(or None in the case of python).
  2. ·        Array indexing starts from 0.

Example:

Input:

arr: 1 2 7 13

Output:

7

Explaination:

No. of balls each row needs      No. of balls each row have

1                                                                                                1

4                                                        2

9                                                        7

16                                                      13

Total number of balls required =0+2+2+3=7. Thus the output is 7.


 class Ballons {
    static  int NumberOfBalls(int [] arr)
    {
        if(arr.length==0)
            return -1;
        double sum=0;
        for(int i=0;i<arr.length;i++)
        {
                      sum=sum+Math.pow(i+1, 2) -arr[i];
        }
        return (int)sum;
    }
    public static void main(String[] args) {
        int arr[]={1,2,7,13};
        int result=NumberOfBalls(arr);
        System.out.println(result);
    }
    
}
/*
OUTPUT
7
*/

Request:-If you found this post helpful then let me know by your comment and share it with your friend. 

If you want to ask a question or want to suggest then type your question or suggestion in comment box so that we could do something new for you all. 

If you have not subscribed my website then please subscribe my website. Try to learn something new and teach something new to other. 

Thanks

Post a Comment

0 Comments