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
}Discussion 0
Join free to post in the discussion.
Related questions
- What a 504 from Nginx meansBackend Developer
- Python default list surpriseBackend Developer
- Signs that a problem suits DPBackend Developer
- What memoisation meansBackend Developer
- What tabulation meansBackend Developer
- Cost of plain recursive FibonacciBackend Developer
- Fibonacci after adding a cacheBackend Developer
- Recursion with no base caseBackend Developer