Bookshelf 2
InterviewTime limit1sMemory limit128 MB
Given up to 20 cow heights and a target bookshelf height B, find the minimum amount by which some subset's total height exceeds or equals B.
- Level
Medium4 of 10
- Topics
- Brute force, Bit manipulation, Array, Greedy
- Solved
- No attempts yet
Problem
Farmer John recently bought another bookshelf for the cow library, but it is filling up quickly, and the only space left is at the very top.
FJ has cows (), where cow has height ( — these are very tall cows). The bookshelf has height , with , where is the sum of the heights of all cows.
To reach the top of the bookshelf, one or more cows can stand on top of one another in a single stack, so that the stack's total height equals the sum of the heights of the cows in it. This total height must be at least for the cows to reach the top.
Because a stack taller than necessary is dangerous, find the set of cows that forms the shortest possible stack that still reaches the shelf. Print the minimal 'excess' height: the difference between the height of this optimal stack and the height of the bookshelf.
Input
- Line 1: two space-separated integers, and .
- Lines 2 to : line contains a single integer .
Output
- A single integer: the non-negative difference between the total height of the optimal set of cows and the height of the bookshelf.
Note
For example, using cows 1, 3, 4, and 5 gives a total height of . A total height of exactly 16 cannot be formed, so the answer is .