From c52cab119a7280858d7c3efce054170c72c6bf42 Mon Sep 17 00:00:00 2001 From: aadil42 <77232799+aadil42@users.noreply.github.com> Date: Sun, 30 Mar 2025 14:41:46 +0530 Subject: [PATCH] Create 2742-painting-the-walls.js Solved painting-the-walls --- javascript/2742-painting-the-walls.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 javascript/2742-painting-the-walls.js diff --git a/javascript/2742-painting-the-walls.js b/javascript/2742-painting-the-walls.js new file mode 100644 index 000000000..340e689ce --- /dev/null +++ b/javascript/2742-painting-the-walls.js @@ -0,0 +1,27 @@ +/** + * DP | Memoization + * Time O(n^2) | Space O(n^2) + * https://leetcode.com/problems/painting-the-walls/ + * @param {number[]} cost + * @param {number[]} time + * @return {number} + */ +var paintWalls = function(cost, time) { + + const cache = new Map(); + + const dfs = (i, remaining) => { + + const hash = `${i},${remaining}`; + + if (cache.has(hash)) return cache.get(hash); + if (remaining <= 0) return 0; + if (i === cost.length) return Infinity; + + const res = Math.min(cost[i] + dfs(i+1, remaining - 1 - time[i]), dfs(i+1, remaining)); + cache.set(hash, res); + return res; + } + + return dfs(0, time.length); +};