Paired Up
InterviewTime limit2sMemory limit512 MB
Pair up M cows with given milk outputs to minimize the maximum sum in any pair, where each pair's time is A+B. Input gives counts and output values in compressed form.
- Level
Medium6 of 10
- Topics
- Greedy, Two pointers, Sorting, Math
- Solved
- No attempts yet
Problem
Farmer John finds that his cows are each easier to milk when they have another cow nearby for moral support. He therefore wants to take his cows (, even) and partition them into pairs. Each pair of cows is then ushered off to a separate stall in the barn for milking. The milking in all stalls takes place simultaneously.
Each cow has its own milk output. If cows with milk outputs and are paired up, it takes a total of units of time to milk them both.
Determine the minimum possible amount of time the entire milking process takes to complete, assuming Farmer John pairs the cows up in the best possible way.
Input
The first line contains (). Each of the next lines contains two integers and , meaning that Farmer John has cows, each with milk output (). The sum of all values is , the total number of cows.
Output
Print the minimum amount of time it takes to milk all the cows, assuming they are paired up optimally.
Hint
In the sample, if the cows with outputs 8 and 2 are paired up, and the two cows with output 5 are paired up, both stalls take 10 units of time for milking. Since milking takes place simultaneously, the entire process completes after 10 units of time. Any other pairing is sub-optimal, because some stall would take more than 10 units of time.