Статья пока доступна только на английском.
Problem Description
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. The only constraint stopping you from robbing every one of them is that adjacent houses have security systems connected, which automatically contact the police if two adjacent houses are broken into on the same night.
You are given an array of numbers representing the amount of money in each house. Return the maximum amount of money you can rob tonight without alerting the police.
Input: number[] (the amount the robber can steal from each house)
Output: number (the maximum amount that can be robbed)
Constraints
- The number of houses (array length) is from 1 to 100
- The amount of money in each house is in the range from 0 to 400
Examples
Input: [1, 2, 3, 1]
Answer: 4
The optimal choice is the first and the third houses.
Brute force approach
The first idea that may come to mind is to generate all possible combinations and evaluate them. This solution has a rather high complexity, since after each house the robber can take two routes: skip one house or skip two. We won't dwell on this approach, since the optimal solution is both simpler to implement and much faster. But since it's the most obvious starting point, here is the implementation:
type Seq = {
index: number;
sum: number;
};
export function robBruteforce(nums: number[]): number {
const sequences = genAllSequences(nums);
let max = 0;
sequences.forEach((sequence) => {
const lastIndex = sequence.length - 1;
if (sequence[lastIndex].sum > max) {
max = sequence[lastIndex].sum;
}
});
return max;
}
function genAllSequences(nums: number[]): Seq[][] {
switch (nums.length) {
case 0:
return [
[
{
index: 0,
sum: 0,
},
],
];
case 1:
return [
[
{
index: 0,
sum: nums[0],
},
],
];
case 2:
return [
[
{
index: 0,
sum: Math.max(nums[0], nums[1]),
},
],
];
}
let res: Seq[][] = [
[
{
index: 0,
sum: nums[0],
},
],
[
{
index: 1,
sum: nums[1],
},
],
[
{
index: 0,
sum: nums[0],
},
{
index: 2,
sum: nums[2] + nums[0],
},
],
];
for (let i = 3; i < nums.length; i++) {
let temp: Seq[][] = [];
res.forEach((sequence) => {
const last = sequence[sequence.length - 1];
if (last.index === i - 2 || last.index === i - 3) {
const tmpSeq = [
...sequence,
{
index: i,
sum: last.sum + nums[i],
},
];
temp.push(tmpSeq);
} else {
temp.push(sequence);
}
});
res = temp;
}
return res;
}Complexity Analysis
Time Complexity
The length of any route can't exceed n/2.
After each house the route may branch in two: go to the house after next or skip two houses.
So the total number of routes can be estimated as 2n/2.
Since we need to go through each of these routes to find the maximum, the overall complexity can also be estimated as O(2n/2).
Space Complexity
Storing all possible routes takes O((n/2) * 2n/2) additional memory.
Optimal approach
This problem can be solved with dynamic programming. The robber can finish either at the last house or at the second-to-last one. That's because along the way the robber can pick either even or odd houses.
Suppose the robber finishes at the last house. How do we find the maximum amount robbed?
The robber can reach the last house either from the 3rd house from the end or from the 4th. So if we know the maximum amount robbed by the 3rd and 4th houses from the end, it's easy to compute the amount for the last house: pick the larger of the two and add the current house. The same principle applies to the 3rd and 4th houses from the end (and to the second-to-last house, in case it's better for the robber to finish there).
Unrolling this logic gives us the optimal solution: if we compute the maximum amount robbed for each house in order from the start of the street, the answer will be in one of the last two elements of the array.
The algorithm is as follows:
- The first 2 elements stay unchanged (since we start from these houses)
- Replace the third element with the sum of the first element and the original value of the third one (since the third house can only be reached from the first)
- For every subsequent element, replace the
i-th element with the sum of its original value and the larger of the elementsi - 2andi - 3 - Return the larger of the last and second-to-last elements.
export function rob(nums: number[]): number {
switch (nums.length) {
case 0:
return 0;
case 1:
return nums[0];
case 2:
return Math.max(nums[0], nums[1]);
}
nums[2] = nums[2] + nums[0];
for (let i = 3; i < nums.length; i++) {
const max = Math.max(nums[i - 2], nums[i - 3]);
nums[i] = max + nums[i];
}
return Math.max(nums[nums.length - 1], nums[nums.length - 2]);
}Complexity Analysis
Time Complexity
To compute the maximum amount, we go through the input array nums once.
So the overall complexity is O(n).
Space Complexity
O(1): the additional memory is constant, since all changes are made in place.