Official Analysis (C++, Java, Python)
Solution
Explanation
The main issue in this problem is figuring out how to efficiently calculate the amount of money FJ earns.
To do this, we can sort our list of cows before starting to process them. In our sorted list, notice that the amount of tuition FJ earns at index (starting from 0) is .
For example, let's look at the sample input:
4 1 6 4 6
If we sort the list so it becomes and take to be , FJ will earn units of money.
With this knowledge, we can now iterate through the list, trying all values of and taking the maximum tuition FJ earns.
Implementation
Time Complexity:
C++
#include <bits/stdc++.h>using namespace std;int main() {int n;cin >> n;vector<int> tuition(n);for (int &t : tuition) { cin >> t; }sort(tuition.begin(), tuition.end());
Java
import java.util.*;public class CowCollege {public static void main(String[] args) {Scanner sc = new Scanner(System.in);int n;n = sc.nextInt();int[] tuition = new int[n];for (int i = 0; i < n; i++) { tuition[i] = sc.nextInt(); }
Python
n = int(input())tuition = sorted(map(int, input().split()))best_tuition = 0best_money = 0for i in range(n):# Apply the formula from the editorialcurr_tuition = tuition[i] * (n - i)if curr_tuition > best_money:best_tuition = tuition[i]best_money = curr_tuitionprint(best_money, best_tuition)
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!