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
Solution:
public class Main {
public static void main(String[] args) {
System.out.println(question(7, 5, new int[]{2, 8, 3, 5, 7, 4, 1, 2})); //Example
}
/**
* @param r represents the number of rats present in an area
* @param unit represents the amount of food each rat consumes
* @param arr represents the amount of food present in ‘i+1’ house number
* @return `-1` - if houses array is null or empty.
* `0` - if the total amount of food from all houses is not sufficient for all the rats.
* `1` - if the household has surplus food for the rats.
*/
public static int question(int r, int unit, int[] arr) {
if (arr == null || arr.length == 0) return -1;
int foodRequired = r * unit;
int foodAvailable = 0;
for (int foodInHouse : arr) {
foodAvailable += foodInHouse;
}
return foodRequired > foodAvailable ? 0 : 1;
}
}
Comments
Leave a comment