House Robber III
The ninja visits an amusement park but finds himself confused because he wants to ride the rides such that he gets maximum fun. The amusement park has only one entrance that is root.
Each ride has a fun number assigned to it and ninja wants to maximize this fun but there is a rule in the park that no one is allowed to ride two directly connected rides.
As the ninja is smart and good in programming because he did a course from coding ninja, he found immediately that park rides are connected like binary tree where the root is the root of the binary tree. Help the ninja to get the maximum fun this time.
Input Format:
The first line of input contains an integer 'T' representing the number of test cases. Then the test cases follow.
The first line of each test case contains a fun number assigned to each ride in the level order form. The line consists of values of nodes separated by a single space. In case a node is null, we take -1 in its place.
For example, the input for the tree depicted in the below image would be :
4
2 6
1 3 5 7
-1 -1 -1 -1 -1 -1
Explanation:
Level 1 :
The root node of the tree is 4
Level 2 :
Left child of 4 = 2
Right child of 4 = 6
Level 3 :
Left child of 2 = 1
Right child of 2 = 3
Left child of 6 = 5
Right child of 6 = 7
Level 4 :
Left child of 1 = null (-1)
Right child of 1 = null (-1)
Left child of 3 = null (-1)
Right child of 3 = null (-1)
Left child of 5 = null (-1)
Right child of 5 = null (-1)
Left child of 7 = null (-1)
Right child of 7 = null (-1)
The first not-null node(of the previous level) is treated as the parent of the first two nodes of the current level. The second not-null node (of the previous level) is treated as the parent node for the next two nodes of the current level and so on.
The input ends when all nodes at the last level are null(-1).
Note:
The above format was just to provide clarity on how the input is formed for a given tree.
The sequence will be put together in a single line separated by a single space. Hence, for the above-depicted tree, the input will be given as:
4 2 6 1 3 5 7 -1 -1 -1 -1 -1 -1
Output Format:
For each test case, print the maximum fun that ninja can get from the amusement park.
The output for each test case is printed in a separate line.
Constraints:
1 <= T <= 5
1 <= N <= 5* 10^3
1 <= DATA <= 10^4
Time limit: 1 sec
- In this approach, we will check all cases one by one using recursion.
- If we do not take a particular ride then we have two choices:
- Either we can also leave its children to ride and move on.
- Or we can visit the children nodes and move on.
- But If we visit a particular ride then we cant ride it children rides.
So we use a recursive function that returns the maximum fun value that can be achievable.
By checking all conditions what if visited a node or not.
Algorithm:
Int maxFun(root, parentVisited ) { If parentVisited = true that means parent node is already visited then we have only one choice return maxFun(root->left,false) + maxFun(root ->right, false) If parentvisited = false that means parent node is not rided Then we have two choice: rided = root.data + maxFun(root.right, true) + maxFun(root.left, true) notRided = maxFun(root.right, false) + maxFun(root.left, false) return max(rided, notRided) }
The idea here is to optimize the previous approach using dynamic programming. We are calling some functions again and again so we will call them once and store their values in a ‘DP’ array.
For example, when calculating RIDED and NOT_RIDED:
RIDED = ROOT.VAL + MAX_FUN(ROOT.LEFT, True) + maxFun(ROOT.RIGHT, True) NOT_RIDED = MAX_FUN(ROOT.LEFT, False) + MAX_FUN(ROOT.RIGHT, False)
The MAX_FUN is called four times. Moreover, when we call MAX_FUN(ROOT.LEFT, True) and MAX_FUN(ROOT.LEFT, False), those two involve the same calculations internally, such as MAX_FUN(NODE.LEFT.LEFT, False).
We can also see this in the below recursive tree:
We see the repetitive calls are made from the recursive tree.
Now we will store our MAX_FUN possible in a hashmap because MAX_FUN is called many times again and again to save time and redundant calculations we store the MAX_FUN in HASH_MAP
So we use a recursive function that returns the maximum fun value that can be achievable.
Algorithm:
Map ‘RIDED_MAP’, ‘NOT_RIDED_MAP’.
Int maxFun(root, parentVisited) { If ‘parentVisited’ = true that means parent node is already visited If ridedMap[root] has already set before then return ridedMap[root] then we have only one choice ridedMap[root] := maxFun(root->left,false) + maxFun(root ->, false) return ridedMap[root] If ‘parentVisited’ = false that means parent node is not rided If notRidedMap[root] has already set before then return notRidedMap[root] Then we have two choice: rided = root.data + maxFun(root.right, true) + maxFun(root.left, true) notRided = maxFun(root.right, false) + maxFun(root.left, false) notRidedMap[root] := max(rided, notRided) return max(rided, notRided) }
The idea here is to use iterative DP but before using iterative DP we need to map or assign an index to each node so that we then able to make a DP array.
We use the most common mapping that is used in heaps and segment trees.
We create an array where nodes are arranged from the BFS suffix.
For example:
Given tree: [39, 84, 35, 5, -1, 95, 9,-1,-1,-1,-1,-1,-1]
Array-based index tree will be like this:
We can achieve this using BFS and storing the node value at a particular index in the array.
Now declare two arrays ‘DP_RIDED’ and ‘DP_NOT_RIDED’ where
DP_RIDED[i] represents maximum fun we can achieve if we start riding from this node and ride this ride.
DP_NOT_RIDED[i] represents maximum fun we can achieve if we start riding from this node and do not ride this ride.
Base Case:
For all leave nodes DP_RIDED[i] = NODE.VAL DP_NOT_RIDED[i] = 0
Transition states:
DP_RIDED[i] = NODE.VAL + ∑ DP_NOT_RIDED[CHILD] DP_NOT_RIDED[i] = ∑ max( DP_RIDED[CHILD], DP_NOT_RIDED[CHILD] )
Algorithm:
- Declare 3 arrays ‘TREE’, ‘DP_RIDED’, ‘DP_NOT_RIDED’.
- Transform the tree from node-base to array-based using simple BFS.
- Using the transition
- DP_RIDED[i] = TREE[i] + ∑ DP_NOT_RIDED[CHILD]
- DP_NOT_RIDED[i] = ∑ max( DP_RIDED[CHILD], DP_NOT_RIDED[CHILD] )
Assign a value to the DP array
- return max(DP_RIDED[0], DP_NOT_RIDED[0])
Description of BFS function
The function will take 3 parameters.
Tree: array to store the tree in an array.
ROOT: binary tree node
CHILDREN_INDEX: a graph that contains an index of the children nodes according to the array-based tree.
int BFS(vector<int> &tree, binaryTreeNode<int> *root, map<int,vector<int>>childrenIndex){ Int index = -1; queue q -> first element is binarytree node and second is parent index while(!q.empty){ index++; currentNode = q.first. Parent = q.second If currentNode is NULL then we will skip this else tree.add(currentNode.data) childrenIndex[parent].add(index) q.add({currentNode.left,index}) q.add({currentNode.right,index}) } return index }