Coding interview questions set 8

Coding interview questions set 8


 Let's begin with set 8,

16)If given a max weight as input find out max allocation from a given array of jewelry weights.


Example 1:

Input:

maxWeight=5

weightArray=[5,2,6]


output:

[{weight:5,qnt:1 }]


Example 2:

Input:

maxWeight=12

weightArray=[5,2,6]


output:

[{weight:5,qnt:2},{weight:2,qnt:1}]


Solution:

function findCombination(maxWeight,weightArray) {

    var myArray = weightArray;

    let finalArray = [];

    for (let i = 0; i < myArray.length; i++) {

        let effectiveWeight = myArray[i];

        let remainder = maxWeight % effectiveWeight;

        let quotient = Math.trunc(maxWeight / effectiveWeight);

        if (quotient > 0) {

            finalArray.push({ weight: myArray[i], qnt: quotient });

        }

        if (remainder == 0) {

            break;

        } else {

            maxWeight = maxWeight - quotient * effectiveWeight;

        }

    }

    return finalArray;

}



Logic:

Here we get quotient and remainder and put quotient and array element in finalArray if quotient>0.

If the remainder is 0 then that is a break condition else we reduce maxWeight by quotient * effectiveWeight.


I hope you like this article.

You may also like these articles:

 Coding Interview Set 1 

 Coding Interview Set 2




Comments

Popular Posts