Answer to Question #303048 in HTML/JavaScript Web Application for sreenu

Question #303048

 The function accepts two positive integers ‘r’ and ‘unit’ and a positive integer array ‘arr’ of size ‘n’ as its argument ‘r’ represents the number of rats present in an area, ‘unit’ is the amount of food each rat consumes and each ith element of array ‘arr’ represents the amount of food present in ‘i+1’ house number, where 0 <= i


Note:


Return -1 if the array is null

Return 0 if the total amount of food from all houses is not sufficient for all the rats.

Computed values lie within the integer range.

Example:


Input:


r: 7

unit: 2

n: 8

arr: 2 8 3 5 7 4 1 2

Output:


4


Explanation:


Total amount of food required for all rats = r * unit

= 7 * 2 = 14.


The amount of food in the 1st 4 houses = 2+8+3+5 = 18. Since, amount of food in 1st 4 houses is sufficient for all the rats. Thus, output is 4.


1
Expert's answer
2022-02-26T11:09:50-0500
const foodForRats = (r, unit, arr) => {
    if (arr.length > 0) {
        const need = r * unit;
        let sum = 0;
        for (let i = 0; i < arr.length; i++) {
            sum += arr[i]
            if (sum >= need) return i + 1
        }
        return 0
    } else return -1
}

console.log(foodForRats(7, 2, [2, 8, 3, 5, 7, 4, 1, 2]))

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS