artshelom2016-12-05 05:52:38
artshelom, 2016-12-05 05:52:38

1005 puzzle, how to solve??

Good afternoon, I can't figure out where the error is in my solution. Here is problem
1005. Pile of stones
Time limit: 1.0 second
Memory limit: 64 MB
You have several stones of known weight w1, …, wn. Write a program that distributes stones into two piles so that the difference between the weights of the two piles is minimal.
Initial data
The input contains the number of stones n (1 ≤ n ≤ 20) and the weights of the stones w1, …, wn (1 ≤ wi ≤ 100 000) — integers separated by spaces.
Your program should print a single number, the minimum difference between the weights of the two heaps.

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        int number = Integer.parseInt(reader.readLine());
        ArrayList<Integer> arr = new ArrayList<>();
        String text = reader.readLine();
        for (int i = 0;i<number;i++) {
            arr.add(Integer.parseInt(text.split(" ")[i]));
        int b = 0;
        for (Integer a:arr){
            if (b >= a){
                b -= a;
                b += a;
        if (b>=0){

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question