There are N houses for sale. The i-th house costs Ai dollars to buy. You have a budget of B dollars to spend.
What is the maximum number of houses you can buy? Round A 2020 Allocation.(Google Kickstart) Google Kickstart compiler runtime error but code working in intellij and other compilers also.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner obj1 = new Scanner(System.in);
int testcases = obj1.nextInt();
for(int testcases1 = 0; testcases1 < testcases;testcases1++){
System.out.println("Case #"+ testcases1+1 +": "+findHouses());
}
obj1.close();
}
private static int findHouses(){
Scanner obj = new Scanner(System.in);
String z = obj.nextLine();
String[] z1 = z.split(" ");
int[] intArray = new int[z1.length];
for (int i = 0; i < z1.length; i++) {
try {
intArray[i] = Integer.parseInt(z1[i]);
} catch (Exception e) {
System.out.println("Unable to parse string to int: " + e.getMessage());
}
}
ArrayList<Integer> houses = new ArrayList<Integer>();
for (int j = 0; j < intArray[0]; j++){
houses.add(obj.nextInt());
}
obj.close();
int sum = 0;
int f = 0;
Collections.sort(houses);
do {
sum += houses.get(f);
if (sum <= intArray[1]){
f++;
}else {
break;
}
}while (houses.size() > f);
return f;
}
}