Skip to content

Instantly share code, notes, and snippets.

@lh0x00
Last active February 25, 2020 16:02
Show Gist options
  • Save lh0x00/eac7a63765c7cd4b13d1933c281e9fa6 to your computer and use it in GitHub Desktop.
Save lh0x00/eac7a63765c7cd4b13d1933c281e9fa6 to your computer and use it in GitHub Desktop.
function getMaxValue(k, n, weights, values) {
let maxValue = 0;
const valueOfItems = {};
for (let i = 0; i < n; i++) {
valueOfItems[i] = values[i] / weights[i];
}
let totalWeight = 0;
const ordered = Object.entries(valueOfItems).sort((a, b) => b[1] - a[1]);
ordered.forEach(([idx]) => {
if (totalWeight + weights[idx] < k && maxValue < n) {
maxValue += values[idx];
totalWeight += weights[idx];
}
});
return maxValue;
}
getMaxValue(10, 6, [5, 7, 6, 1, 2, 3], [1, 3, 2, 2, 3, 4]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment