Skip to content

Create 2742-painting-the-walls.js #3979

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions javascript/2742-painting-the-walls.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/**
* DP | Memoization
* Time O(n^2) | Space O(n^2)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can optimize space

/**
 * DP - Bottom Up
 * Array - Tabulation
 * Time O(N^2) | Space O(N)
 * @param {number[]} cost
 * @param {number[]} time
 * @return {number}
 */
var paintWalls = (cost, time) => {
    const tabu = initTabu(cost);

    for (let i = 0; (i < cost.length); i++) {
        for (let remain = cost.length; (0 < remain); remain--) {
            const left = tabu[Math.max(((remain - 1) - time[i]), 0)] + cost[i];
            const right = tabu[remain];

            tabu[remain] = Math.min(left, right);
        }
    }

    return tabu[cost.length];
}

var initTabu = ({ length }) => {
    const tabu = new Array(length + 1).fill(Number.MAX_SAFE_INTEGER);

    tabu[0] = 0;

    return tabu;
}

* 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);
};