[Algorithm] Max icons to include: Dynamic programming

Saying that we have some icons

[Algorithm] Max icons to include: Dynamic programming

and a target sum, for example 16.

 

How to choose which and how many icons to include to reach the target but minize the numbers of icons.

EXP: 3 * 5$ icons 

        +

  1 * 1$icon

-------------

total 4 icons.

 

Idea is 

 Wheather should include current icon.

[Algorithm] Max icons to include: Dynamic programming

 

const Pair = (i, t) => `Pair(${i}, ${t})`;

const iconsToInclude = (nums, total) => {
  let cache = {};
  const doWork = (i, t) => {
    const p = Pair(i, t);
    if (p in cache) {
      return cache[p];
    }
    if (i === 0 || t === 0 || nums[i] > t) {
      return Number.MAX_SAFE_INTEGER;
    }
    if (t === 1 || nums[i] === t) {
      return 1;
    }
    let toInclude = 0
    let notToInclude = 0;
    let res = 0;
    toInclude = doWork(i, t - nums[i]) + 1;
    notToInclude = doWork(i - 1, t);
    res = Math.min(toInclude, notToInclude);
    cache[Pair(i, t)] = res;
    return res;
  }
  return doWork(nums.length - 1, total);
}

console.log(iconsToInclude([25, 16, 5, 1], 33));

 

上一篇:操作系统 Programming Project 5 多线程排序


下一篇:CodeForces - 730I Olympiad in Programming and Sports(最大费用最小流)