House Robber IV
House Robber IV is a medium binary search problem solved with the binary search on answer space pattern.
The best approach, optimal (binary search on the capability), runs in O(n log M) time and O(1) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force (try every value) up.
Problem
Houses stand in a row, and nums[i] is the amount of money in house i. A robber plans to rob at least k houses, but never two houses that are next to each other.
The capability of a plan is the largest amount taken from any single house in that plan.
Return the minimum capability over all plans that rob at least k houses. It is guaranteed that at least one such plan exists.
Examples
Example 1
- Input
nums = [3, 7, 2, 9, 4], k = 2- Output
3- Why
- Rob the houses holding 3 and 2 (positions 0 and 2). They are not next to each other, and the bigger amount is 3. Any pair without both of them includes a house worth 4 or more.
Example 2
- Input
nums = [5, 1, 8, 6, 2, 9], k = 3- Output
8- Why
- Three houses with no two side by side must use positions like 0, 2, 4 or 1, 3, 5. The set 5, 8, 2 has a largest value of 8, and no choice keeps every house at 6 or less.
Example 3
- Input
nums = [4], k = 1- Output
4- Why
- There is one house and it must be robbed.
Constraints
1 <= nums.length <= 10^51 <= nums[i] <= 10^91 <= k <= (nums.length + 1) / 2
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 12 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (try every value) | O(n²) | O(n) |
| Optimal (binary search on the capability) | O(n log M) | O(1) |
1Brute force (try every value)
O(n²)Up to n candidates, and each count walks the whole array once. Sorting adds O(n log n).O(n)The sorted copy of the values.The answer is always one of the house values, because the capability is the largest robbed amount. Sort the values and try them from the smallest. For each candidate cap, count how many houses you can rob using only houses worth at most cap, never two side by side. The first cap that reaches k houses is the answer.
- Copy nums and sort the copy.
- For each value cap in that order, count houses greedily: walk left to right, and when nums[i] <= cap, rob it and jump over position i + 1.
- Return the first cap whose count is at least k.
class Solution {
public int minCapability(int[] nums, int k) {
int[] values = nums.clone();
Arrays.sort(values);
for (int cap : values) {
if (countHouses(nums, cap) >= k) return cap;
}
return values[values.length - 1];
}
// rob every house worth at most cap, skipping the house right after each one robbed
private int countHouses(int[] nums, int cap) {
int count = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] <= cap) {
count++;
i++;
}
}
return count;
}
}class Solution:
def minCapability(self, nums: List[int], k: int) -> int:
values = sorted(nums)
for cap in values:
if self.countHouses(nums, cap) >= k:
return cap
return values[-1]
# rob every house worth at most cap, skipping the house right after each one robbed
def countHouses(self, nums: List[int], cap: int) -> int:
count = 0
i = 0
while i < len(nums):
if nums[i] <= cap:
count += 1
i += 1
i += 1
return countclass Solution {
public:
int minCapability(vector<int>& nums, int k) {
vector<int> values = nums;
sort(values.begin(), values.end());
for (int cap : values) {
if (countHouses(nums, cap) >= k) return cap;
}
return values.back();
}
private:
// rob every house worth at most cap, skipping the house right after each one robbed
int countHouses(vector<int>& nums, int cap) {
int count = 0;
for (int i = 0; i < (int)nums.size(); i++) {
if (nums[i] <= cap) {
count++;
i++;
}
}
return count;
}
};function minCapability(nums, k) {
const values = [...nums].sort((a, b) => a - b);
for (const cap of values) {
if (countHouses(nums, cap) >= k) return cap;
}
return values[values.length - 1];
}
// rob every house worth at most cap, skipping the house right after each one robbed
function countHouses(nums, cap) {
let count = 0;
for (let i = 0; i < nums.length; i++) {
if (nums[i] <= cap) {
count++;
i++;
}
}
return count;
}2Optimal (binary search on the capability)
O(n log M)About log of the value range (at most around 30) checks, each a single pass over the array.O(1)Only a few integer variables.The greedy count can only go up as cap goes up: a bigger cap allows every house a smaller cap allowed, and maybe more. So the caps split into a block that fails followed by a block that works. Binary search between the smallest and the largest value for the first cap that works, using the same greedy count as the check.
- lo = smallest value, hi = largest value. hi always works, because then every house is allowed and k is at most (n + 1) / 2.
- mid = lo + (hi - lo) / 2. If countHouses(mid) >= k, the answer is mid or lower: hi = mid. Otherwise lo = mid + 1.
- When lo meets hi, return it. It is a house value, since the smallest working cap always equals some house.
class Solution {
public int minCapability(int[] nums, int k) {
int lo = Integer.MAX_VALUE, hi = 0;
for (int x : nums) {
lo = Math.min(lo, x);
hi = Math.max(hi, x);
}
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (countHouses(nums, mid) >= k) hi = mid;
else lo = mid + 1;
}
return lo;
}
// rob every house worth at most cap, skipping the house right after each one robbed
private int countHouses(int[] nums, int cap) {
int count = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] <= cap) {
count++;
i++;
}
}
return count;
}
}class Solution:
def minCapability(self, nums: List[int], k: int) -> int:
lo, hi = min(nums), max(nums)
while lo < hi:
mid = (lo + hi) // 2
if self.countHouses(nums, mid) >= k:
hi = mid
else:
lo = mid + 1
return lo
# rob every house worth at most cap, skipping the house right after each one robbed
def countHouses(self, nums: List[int], cap: int) -> int:
count = 0
i = 0
while i < len(nums):
if nums[i] <= cap:
count += 1
i += 1
i += 1
return countclass Solution {
public:
int minCapability(vector<int>& nums, int k) {
int lo = INT_MAX, hi = 0;
for (int x : nums) {
lo = min(lo, x);
hi = max(hi, x);
}
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (countHouses(nums, mid) >= k) hi = mid;
else lo = mid + 1;
}
return lo;
}
private:
// rob every house worth at most cap, skipping the house right after each one robbed
int countHouses(vector<int>& nums, int cap) {
int count = 0;
for (int i = 0; i < (int)nums.size(); i++) {
if (nums[i] <= cap) {
count++;
i++;
}
}
return count;
}
};function minCapability(nums, k) {
let lo = Infinity, hi = 0;
for (const x of nums) {
lo = Math.min(lo, x);
hi = Math.max(hi, x);
}
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (countHouses(nums, mid) >= k) hi = mid;
else lo = mid + 1;
}
return lo;
}
// rob every house worth at most cap, skipping the house right after each one robbed
function countHouses(nums, cap) {
let count = 0;
for (let i = 0; i < nums.length; i++) {
if (nums[i] <= cap) {
count++;
i++;
}
}
return count;
}Edge cases to test
- A single house (answer nums[0])
- k = 1: the answer is the smallest value
- k as large as allowed with an odd length: every other house from position 0
- Many equal values
- The smallest values sit next to each other, so they cannot all be used
Hints
Hint 1
Turn it around: for a fixed capability cap, how many houses can you rob if you may only touch houses worth at most cap?
Hint 2
That count only grows as cap grows. So the answer is the smallest cap whose count reaches k, and you can binary search for it.
Hint 3
To count, walk left to right and rob every house you can afford, then skip its neighbour. Taking the earliest allowed house never hurts.
FAQ
What is the best time complexity for House Robber IV?
Optimal (binary search on the capability) runs in O(n log M) time and O(1) extra space. About log of the value range (at most around 30) checks, each a single pass over the array.
Which pattern does House Robber IV use?
It is a binary search problem that uses the binary search on answer space pattern. Other problems with the same pattern: Koko Eating Bananas, Minimum Number of Days to Make m Bouquets, Separate Squares I.
Is there a brute force solution for House Robber IV?
Yes. Brute force (try every value) takes O(n²) time and O(n) space. The answer is always one of the house values, because the capability is the largest robbed amount.
Which edge cases should I test for House Robber IV?
A single house (answer nums[0]); k = 1: the answer is the smallest value; k as large as allowed with an odd length: every other house from position 0; Many equal values; The smallest values sit next to each other, so they cannot all be used.