Skip to content
RED SAG Skills
medium10 pts · first answer countsdynamic-programmingmemoizationdebugging

Cache key that forgets an argument

This memoised function returns wrong answers for some inputs. What is the bug?

const memo = new Map()
function best(i, k) {          // k = discounts left
  if (i === items.length) return 0
  if (memo.has(i)) return memo.get(i)
  let r = items[i] + best(i + 1, k)
  if (k > 0) r = Math.min(r, items[i] / 2 + best(i + 1, k - 1))
  memo.set(i, r)
  return r
}
Choose one answer

Discussion 0

Join free to post in the discussion.

Related questions