Leetcode House Robber III

Source: Internet
Author: User

The original title link is here: https://leetcode.com/problems/house-robber-iii/

Topic:

The thief has found himself a new place for his thievery again. There is a entrance to this area, called the "root." Besides the root, each house have one and only one parent house. After a tour, the Smart thief realized the ' all houses in this ' place forms a binary tree. It would automatically contact the police if and directly-linked houses were broken into on the same night.

Determine the maximum amount of money the thief can rob tonight without alerting the police.

Example 1:

     3    /    2   3    \   \      3   1

Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.

Example 2:

     3    /    4   5  /\   \  1   3   1

Maximum amount of money the thief can rob = 4 + 5 = 9.

Exercises

Robroot = notrobleft + notrobright + root.val

Notrobroot = Math.max (Robleft, Notrobleft) + Math.max (Robright, Notrobright).

Dfs from the tree is updated from the bottom up.

Time Complexity:o (n). Space:o (LOGN). The LOGN layer stack is used.

AC Java:

1 /**2 * Definition for a binary tree node.3 * public class TreeNode {4 * int val;5 * TreeNode left;6 * TreeNode right;7 * TreeNode (int x) {val = x;}8  * }9  */Ten  Public classSolution { One      Public intRob (TreeNode root) { A         int[] res =Dfs (root); -         returnMath.max (Res[0], res[1]); -     } the     Private int[] DFS (TreeNode root) { -         int[] DP =New int[2]; -         if(Root = =NULL){ -             returnDP; +         } -         int[] left =DFS (root.left); +         int[] right =DFS (root.right); A         //dp[0] means stealing root, then can't steal around, so use left[1], right[1]. atDp[0] = left[1] + right[1] +Root.val; -         //dp[1] means not to steal root, then the right or left to steal can, take the maximum value -DP[1] = Math.max (left[0], left[1]) + Math.max (right[0], right[1]); -         returnDP; -     } -}

Similar to house robber, house robber Ii.

Leetcode House Robber III

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.