DEV Community

codingpineapple
codingpineapple

Posted on

2 2

LeetCode 337. House Robber III (javascript solution)

Description:

The thief has found himself a new place for his thievery again. There is only one entrance to this area, called root.

Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if two directly-linked houses were broken into on the same night.

Given the root of the binary tree, return the maximum amount of money the thief can rob without alerting the police.

Solution:

Time Complexity : O(n)
Space Complexity: O(n)

 var rob = function(root) {
    // Choose between using values at root + grandchildren (current) or using values from children (next)
    const { current, next } = traverse(root);

    return Math.max(current, next);
};

function traverse(root) {
    // If there is not root ther is no root value or grandchildren values (current) and there are also no children values (next)
    if (!root) {
        return { current: 0, next: 0 };
    }

    // Get values for children
    const left = traverse(root.left);
    const right = traverse(root.right);

    // Value if we include the root node in our robbing path
    const current = root.val + left.next + right.next;

    // Max Value if we include the children in our robbing path
    const next = Math.max(left.current, left.next) + Math.max(right.current, right.next);

    return { current, next };
}
Enter fullscreen mode Exit fullscreen mode

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay