Advertisement
socialgraph

D

Sep 12th, 2021
649
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. module.exports = (maxAmount, costs) => {
  2.     const minCost = Math.min(...costs);
  3.     let maxCount = (maxAmount / minCost | 0);
  4.     if (!maxCount) {
  5.         return '';
  6.     }
  7.     maxAmount -= maxCount * minCost;
  8.     costs = costs.map((cost) => cost - minCost);
  9.  
  10.     let byCost = Array.from({length: costs.length}, (_, i) => i);
  11.     byCost.sort((i, j) => {
  12.         return (costs[i] > costs[j] || (costs[i] === costs[j] && i < j)) ? 1 : -1;
  13.     });
  14.  
  15.     let maxUniqueCount = 0;
  16.     {
  17.         let amount = maxAmount;
  18.         for (let i of byCost) {
  19.             amount -= costs[i];
  20.             if (amount < 0) {
  21.                 break;
  22.             }
  23.             maxUniqueCount++;
  24.             if (maxCount === maxUniqueCount) {
  25.                 break;
  26.             }
  27.         }
  28.     }
  29.  
  30.     const k = byCost[0];
  31.     byCost = byCost.slice(1);
  32.     maxUniqueCount--;
  33.  
  34.     let counts = Array(costs.length).fill(0);
  35.     counts[k] = maxCount;
  36.  
  37.     for (let i = costs.length - 1; i >= 0 && maxUniqueCount > 0; i--) if (i !== k && costs[i] <= maxAmount) {
  38.         let amount = maxAmount - costs[i];
  39.         let uniqueCount = maxUniqueCount - 1;
  40.         if (uniqueCount > 0) {
  41.             for (let j of byCost) if (j < i) {
  42.                 uniqueCount--;
  43.                 amount -= costs[j];
  44.                 if (!uniqueCount) {
  45.                     break;
  46.                 }
  47.             }
  48.         }
  49.         if (amount < 0 || uniqueCount > 0) {
  50.             continue;
  51.         }
  52.         let count = 1;
  53.         if (i > k) {
  54.             count += (amount / costs[i] | 0);
  55.         }
  56.         count = Math.min(count, counts[k] - maxUniqueCount)
  57.         counts[i] += count;
  58.         counts[k] -= count;
  59.  
  60.         maxAmount -= counts[i] * costs[i];
  61.         maxUniqueCount--;
  62.     }
  63.  
  64.     let message = [];
  65.     for (let i = costs.length - 1; i >= 0; i--) {
  66.         message = [...message, ...Array(counts[i]).fill(i + 1)];
  67.     }
  68.     return message.join('')
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement