![]() |
VOOZH | about |
Given an array arr[] which represents houses arranged in a circle, where each house has a certain value. A thief aims to maximize the total stolen value without robbing two adjacent houses. Since the houses are in a circle, the first and last houses are also considered adjacent. Determine the maximum amount the thief can steal.
Examples:
Input: arr[] = [2, 2, 3, 1, 2]
Output: 5
Explanation: Maximum stolen value: arr[0] + arr[2] = 2 + 3 = 5 or arr[2] + arr[4] = 3 + 2 = 5.Input: arr[] = [2, 3, 2]
Output: 3
Explanation: arr[0] and arr[2] can't be robbed simultaneously because they are adjacent houses.
Table of Content
The idea is to solve this problem by handling the circular constraint, where the first and last houses are adjacent.
To avoid robbing both of them together, we divide the problem into two linear cases:
- Consider houses from index 0 to nβ2 (exclude the last house).
- Consider houses from index 1 to nβ1 (exclude the first house).
For each case, the thief has two choices at every house:
- Rob the current house β then skip the adjacent (previous) one and add the value of the current house.
- Skip the current house β take the maximum value obtained so far.
We solve both cases separately using recursion and then take the maximum of the two results.
5
In the recursive solution, there are many overlapping subproblems because the same states are solved multiple times.
To avoid this repetition, we can use memoization where we store the results of already computed subproblems in a separate array (memo). Before solving any subproblem, we first check in the memo[i] if it has been computed earlier. If yes, we simply reuse the stored result instead of recalculating it.
5
The main idea is to build the solution iteratively using a DP table where each entry represents the maximum money that can be stolen up to that house.
The relation that helps us compute this is: dp[j] = max(arr[j] + dp[j-2], dp[j-1])
This ensures we always choose the option that gives the maximum total amount without robbing two adjacent houses.
The formula dp[j] = max(arr[j] + dp[jβ2], dp[jβ1]) comes from two choices:
We take the maximum of these two options to ensure the thief always gets the highest possible amount.
5
In the previous approach, we used an array to store results for all states. However, if we look closely, to calculate the result for the current house, we only need the values from the previous two houses.This means thereβs no need to store all previous results.
We can simply keep track of the last two computed values and update them as we move forward.
5