Maximizing Productivity - FEB 2024 Bronze - Java vs Python

Hi I am trying to do this problem in Java https://usaco.org/index.php?page=viewproblem2&cpid=1397 which did not pass the time limit for test 5 to 17. But the weird thing is when I coded the same solution in Python it passed all 17 test cases.

I wonder if someone can help if I messed up somewhere in my Java code?

Java Solution

import java.util.*;

public class MaximizingProductivity2 {
    public void yesOrNo(Scanner scanner, int numOfFarms, int numOfQueries) {
        List<Integer> farms = new ArrayList<>(numOfFarms);
        StringTokenizer closingTimes = new StringTokenizer(scanner.nextLine()," ");

        StringTokenizer visitTimes = new StringTokenizer(scanner.nextLine()," ");
        for (int i = 0; i < numOfFarms; i++) {
            farms.add(Integer.parseInt(closingTimes.nextToken())-Integer.parseInt(visitTimes.nextToken()));
        }
        closingTimes = null;
        visitTimes = null;
        Collections.sort(farms, Collections.reverseOrder());

        for (int i = 0; i < numOfQueries; i++) {
            String line = scanner.nextLine();
            StringTokenizer queryString = new StringTokenizer(line, " ");

            int v = Integer.parseInt(queryString.nextToken());
            int s = Integer.parseInt(queryString.nextToken());
            if(farms.get(v-1) > s) {
                System.out.println("YES");
            } else {
                System.out.println("NO");
            }
        }
    }
    public static void main(String[] args) {
        MaximizingProductivity2 mp = new MaximizingProductivity2();
        Scanner s = new Scanner(System.in);
        StringTokenizer firstLine = new StringTokenizer(s.nextLine(), " ");

        int numOfFarms = Integer.parseInt(firstLine.nextToken());
        int numOfQueries = Integer.parseInt(firstLine.nextToken());

        mp.yesOrNo(s, numOfFarms, numOfQueries);
    }
}

Python Solution

N, Q = (int(x) for x in input().split())
c = [int(x) for x in input().split()]
t = [int(x) for x in input().split()]
diffs = sorted([ci - ti for ci, ti in zip(c, t)], reverse=True)
for _ in range(Q):
    V, S = (int(x) for x in input().split())
    if diffs[V-1] > S:
        print("YES")
    else:
        print("NO")

You might need a faster method of input in Java?

https://usaco.org/index.php?page=instructions

  • For some of the more advanced problems with larger input sizes, competitors may benefit from using fast input/output, to more easily pass within the time limit. For C++ users, you may want to add “ios_base::sync_with_stdio(false); cin.tie(0);” to the top of your main method if you are using cin/cout. For Java users, you may want to use BufferedReader instead of Scanner.

Example Code: Input & Output