0

I'd like to know how I can express a minimum sum of each coefficient. Sum must be zero, and the list's integer can be multiplied with each coefficient.

For ex : (-5, -2, 3, 7) to make sum as 0,

if -5 has coefficient 2,
3 has coefficient 1, 7 has coefficient 1 then -5*2 +3*1+7*1= 0, and sum of coefficient will be 2+1+1=4.

Also, if -5 has coefficient 1,
-2 has coefficient 1, 7 has coefficient 1 then -5*1 +(-2*1)+7*1= 0, and sum of coefficient will be 1+1+1=3.

Therefore, the most minimum sum of coefficients will be 3.

I thought that this problem can be solved as like coin changing algorithm.

So I decided to modify the coin changing algorithm code. the below is coin changing algorithm sample code.

I used arraylist before, then, I saw the advice, so I modified code as using hashmap as like. But, the problem is the coin contains (-) minus value, and sum must be zero, so below codes occured error.

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map.Entry;

public class CoinChange {

    public static void main(String[] args) {
        int[] coins = {-37,35,2,5};       
        int amt = 0;       
        makeChange(coins, amt); 
    }

    public static void makeChange(int[] coins, int amount){
        //Sorting the coins
        Arrays.sort(coins);//[-37, 2, 5, 35]
        //System.out.println(Arrays.toString(coins));
        //System.out.println(amount);

        int n = coins.length - 1;


        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();

        while(amount > 0)
        {
            if(coins[n] <= amount)
            {
                int val = 1;
                if(map.containsKey(coins[n]))
                {
                    val = map.get(coins[n]);
                    val = val+1;
                }

                map.put(coins[n], val);

                amount = amount - coins[n];

            }
            else
            {
                n--;
            }

        }

        for(Entry<Integer, Integer> entry: map.entrySet()){

            System.out.println(entry.getKey() +":" + entry.getValue());
        }
    }
}
hohotiger
  • 11
  • 2
  • Have you considered using a [`Map`](https://docs.oracle.com/javase/8/docs/api/java/util/Map.html) instead of array? – Nikolay K Jun 17 '17 at 14:37
  • @NikolayKondratyev Thanks! I followed your advice as using map, but although I used map, I still have problem. – hohotiger Jun 18 '17 at 16:54

0 Answers0