Given a rod of length n, maximize the total number of segments can be cutted in length of x, y, and z.
This algorithm uses memoization to improve performance. It's same as the recursive version of Maximize number segments of cutted in length x, y and z, but with a special 'cache' to store results. The 'cache key' is crucial. It's how we identify and store past results. Sometimes we need one key, sometimes multiple keys. We add code to:
cache = None def cut(n, x, y, z): if n <= 0: return 0 global cache if not cache: cache = [float('-inf')] * (n + 1) if cache[n] == float('-inf'): cache[n] = 1 + max(cut(n - x, x, y, z), cut(n - y, x, y, z), cut(n - z, x, y, z)) return cache[n] n = 4 x = 2 y = 1 z = 1 print(cut(n, x, y, z))
let cache = null; function cut(n, x, y, z) { if (n <= 0) { return 0; } if (!cache) { cache = Array(n + 1); } if (!cache[n]) { cache[n] = 1 + Math.max(cut(n - x, x, y, z), cut(n - y, x, y, z), cut(n - z, x, y, z)); } return cache[n]; } const n = 4; const x = 2; const y = 1; const z = 1; console.log(cut(n, x, y, z));