JSFiddle - React, Tailwind, and code Playground

by IPWright83

HTML

https://www.interviewcake.com/question/javascript/cake-thief

JavaScript

maxDuffelBagValue = function(cakeTypes) {
     
     cakeTypes.forEach(c => c.ratio = c.value / c.weight);
     cakeTypes = cakeTypes.sort((a, b) => a.ratio < b.ratio);
     
     var totalWeight = 0;
     var value = 0;
     
     while(totalWeight < capacity) {
     	  
        // Find the most valueable cake
        var added = false;
        for(var cakeIndex = 0; cakeIndex < cakeTypes.length; cakeIndex++) {
           var cake = cakeTypes[cakeIndex];
           if(totalWeight + cake.weight <= capacity) {
              value += cake.value;
              totalWeight += cake.weight;
              added = true;
              break;
           }
        }
        
        // Can't fill the bag
        if(!added) {
           return value;
        }
     }
     
     return value;
  };
  
  var cakeTypes = [
    {weight: 7, value: 160},
    {weight: 3, value: 90},
    {weight: 2, value: 15},
];

var capacity = 20;

const result = maxDuffelBagValue(cakeTypes, capacity);
console.log(result);