Java Code Compile Issue

HackerRank says:

The first line contains two space-separated integers describing the respective values of `n` (the number of dirty plates) and `k` (the number of plates Harold has time to wash).

• 1 <= `n` <= 20000, 1 <= `k` <= 20000

However, your code is doing something totally different:

``````String s = in.next();
int l = s.length();
int n = s.charAt(0);
int k = s.charAt(l - 1);
``````

Since `next()` only reads one token, `s` would be the String value of the HackerRank value `n`.

Let’s say the first line is:

``````7000 20000
``````

Your code will read `7000` into `s`, then assign `n = '7'` and `k = '0'`.

The character `'7'` has the ASCII/Unicode numeric value `55`, and the character `'0'` has value `48`. So what you really got was `n = 55` and `k = 48`.

What you should have done, is simply this:

``````int n = in.nextInt();
int k = in.nextInt();
``````

UPDATE

Since the contest is over, you can read the editorial page to see a solution. Java doesn’t have a `multiset` (ordered list), but you could use a `PriorityQueue`.

Below is an alternate solution with a lower memory footprint for high values of `k`.

First, assume you can wash all the plates, so sum all the `p` values. If `k >= n`, you’re done. Now, for every plate you can’t wash, subtract `p` again and also subtract `d`, e.g. subtract `p + d` from the total.

The goal then is to wash the plates with the highest `p + d` value first, so we’ll be subtracting smaller values from the total. To do that, build an array of `p + d` values, sort it, and wash/remove/skip the `k` plates with the highest values.

Finally, remember to not return a negative value.

Here it is in compact form:

``````java.util.Scanner in = new java.util.Scanner(System.in);
int n = in.nextInt(), k = in.nextInt(), pd[] = new int[n];
long total = 0;
for (int i = 0; i < n; i++) {
int p = in.nextInt(), d = in.nextInt();
total += p;
pd[i] = p + d;
}
java.util.Arrays.sort(pd);
for (int i = n - k - 1; i >= 0; i--)
total -= pd[i];
System.out.println(Math.max(0, total));
``````