All problems

Problem 455

Last Stone Weight II

Medium · 20 pts · Array, Dynamic Programming

Problem

You have stones with given weights. In each turn you choose any two stones and smash them together: if their weights are x <= y, the stone of weight x is destroyed and the other becomes y - x (or both are destroyed if x = y). Continue until at most one stone is left, and print the smallest possible weight of that stone (0 if no stone is left). Smashing in any order amounts to splitting the stones into two groups and taking the difference of their sums, so you want the subset sum closest to half the total.

Input

First line: N. Second line: N stone weights.

Output

Print the smallest possible final weight.

Constraints

1 <= N <= 30; 1 <= weight <= 100

Example input

6
2 7 4 1 8 1

Example output

1

Explanation

The stones 2 7 4 1 8 1 add up to 23. They can be split into the groups {8, 1, 2} with sum 11 and {7, 4, 1} with sum 12, whose difference is 1. An odd total can never be split evenly, so 1 is the smallest possible final weight.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Ones and Zeroes Next: Stock Trading with Cooldown