Skip to main content

Command Palette

Search for a command to run...

possible Sums

Published
•2 min read•View as Markdown
possible Sums
D

I am a Software Engineer currently looking out for jobs around seattle, Washington.

You have a collection of coins, and you know the values of the coins and the quantity of each type of coin in it. You want to know how many distinct sums you can make from non-empty groupings of these coins.

Example

For coins = [10, 50, 100] and quantity = [1, 2, 1], the output should be
solution(coins, quantity) = 9.

Here are all the possible sums:

  • 50 = 50;

  • 10 + 50 = 60;

  • 50 + 100 = 150;

  • 10 + 50 + 100 = 160;

  • 50 + 50 = 100;

  • 10 + 50 + 50 = 110;

  • 50 + 50 + 100 = 200;

  • 10 + 50 + 50 + 100 = 210;

  • 10 = 10;

  • 100 = 100;

  • 10 + 100 = 110.

int solution(int[] coins, int[] quantity) {
    // Create a HashSet to store all the possible sums
    HashSet<Integer> sums = new HashSet<Integer>();
    // Add 0 as a possible sum, as we can always make a sum of 0
    sums.add(0);

    // Loop through all the coins
    for(int i=0; i<coins.length; i++) {
        // Get the value of the current coin
        int coin = coins[i];
        // Create a new HashSet to store the current set of sums
        HashSet<Integer> currentSums = new HashSet<Integer>();
        // Loop through all the previous possible sums
        for(Integer sum : sums) {
            // Loop through the quantity of the current coin
            for(int j=1; j<=quantity[i]; j++) {
                // Add a new sum to the current set of sums
                // by adding the current coin multiplied by the quantity
                currentSums.add(sum + coin*j);
            }
        }
        // Add all the new sums to the main set of sums
        sums.addAll(currentSums);
    }

    // Return the size of the set of sums, minus 1 (to exclude the 0 sum we added earlier)
    return sums.size() - 1;
}

Time complexity - O(m*n*sum.size())

Interview Problems

Part 12 of 17

In this series we will be exploring interview problems asked by various companies. This will be a complete random series and topics will vary from one Data structure to other. Stay tuned!!

Up next

digitTreeSum

We're going to store numbers in a tree. Each node in this tree will store a single digit (from 0 to 9), and each path from root to leaf encodes a non-negative integer. Given a binary tree t, find the sum of all the numbers encoded in it. Link for the...

More from this blog

Boolean's Blog

27 posts