USACO 2022 December Contest, Bronze Problem 1. Cow College

USACO 2022 December Contest, Bronze

Problem 1. Cow College

I am using java and here is my code:
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;

public class college {
public static void main (String[] args)throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
long[] max = new long[n];
long[] answers = new long[n];
for(int i=0; i<n;i++) {
max[i]=Long.parseLong(st.nextToken());
}
Arrays.sort(max);
for(int i=0; i<n; i++) {
long current=max[i];
for(int j=0; j<n; j++) {
if(max[j]>=current){
answers[i]+=current;
}
}
}
ArrayList answers2=new ArrayList();
for(int i=0;i<n;i++) {
answers2.add(answers[i]);
}
Arrays.sort(answers);
System.out.print(answers[n-1]);
System.out.print(" ");
System.out.print(max[answers2.indexOf(answers[n-1])]);
}
}
My code gets the following results:


I don’t know how to optimize the runtime so that it gets all green. Could someone help me with this?

Notice this: If you sort the list of numbers, and set the first cow’s (the lowest) maximum amount willing to pay as the tuition for the college, then how can you calculate the amount Farmer John will make in constant time? You can use the strategy used to solve the problem above to solve the whole problem in O(NlogN) time.

Also, this won’t be the difference between time out and AC, but you don’t need the answers and answers2 Arrays/ArrayLists. Keeping track of the highest revenue and the cost/cow for that amount of revenue using two variables is better.

1 Like

okay, thanks