I’m receiving a runtime error with this program. This runs just fine for smaller straight forward inputs. However, when submitting the program, I’m receiving a Runtime error.
Here is my code in Java:
class Codechef
{
public static void main (String args) throws java.lang.Exception
{
Scanner read = new Scanner(System.in);
int limit = read.nextInt();
int i = 0;
while(i<limit) {
int plates = read.nextInt();
long mBalls = read.nextLong();
long arr = new long[plates];
for (int loop=0; loop<plates; loop++) {
arr[loop] = read.nextInt();
}
Arrays.sort(arr);
long total = 0;
long out = 0;
while (plates>=0) {
out = out + 1;
total = total + arr[–plates];
if (total >= mBalls) {
plates = -1;
}
}
if (total >= mBalls) {
System.out.println(out);
} else {
System.out.println(-1);
}
i = i + 1;
}
}
}
I fixed it now:
class Codechef
{
public static void main (String args) throws java.lang.Exception
{
Scanner read = new Scanner(System.in);
int limit = read.nextInt();
int i = 0;
int loop = 0;
while(i<limit) {
int plates = read.nextInt();
long mBalls = read.nextLong();
long arr = new long[plates];
for (loop=0; loop<plates; loop++) {
arr[loop] = read.nextLong();
}
Arrays.sort(arr);
long total = 0;
long out = 0;
int idx = plates - 1;
while (idx>=0) {
out = out + 1;
total = total + arr[idx];
if (total >= mBalls) {
idx = -1;
}
–idx;
}
if (total >= mBalls) {
System.out.println(out);
} else {
System.out.println(-1);
}
i = i + 1;
}
read.close();
}
}