Problem
There are several consecutive houses along a street, each of which has some money inside. There is also a robber, who wants to steal money from the homes, but he refuses to steal from adjacent homes.
The capability of the robber is the maximum amount of money he steals from one house of all the houses he robbed.
You are given an integer array nums
representing how much money is stashed in each house. More formally, the ith
house from the left has nums[i]
dollars.
You are also given an integer k
, representing the minimum number of houses the robber will steal from. It is always possible to steal at least k
houses.
Return the minimum capability of the robber out of all the possible ways to steal at least k
houses.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints
1 <= nums.length <= 105
1 <= nums[i] <= 109
1 <= k <= (nums.length + 1)/2
Similar Problems
House Robber House Robber 2 - Houses in circle House Robber 3 - Houses in Binary Tree
Solution
Method 1 - Greedy
To solve this problem effectively, we need to determine the minimum possible capability of the robber such that he can steal from at least k
houses, while respecting the condition of not robbing two adjacent houses.
Approach
- Binary Search on Capability:
- The idea is to use binary search to find the minimum “capability” (
cap
). Here,cap
represents the maximum amount the robber steals in a single house across all the selected houses. - For a given capability, we check if it is feasible to rob at least
k
houses:- To check feasibility, we utilise a greedy approach where we simulate robbing each house only if the amount in that house is ≤
cap
, without selecting adjacent houses.
- To check feasibility, we utilise a greedy approach where we simulate robbing each house only if the amount in that house is ≤
- The idea is to use binary search to find the minimum “capability” (
- Key Functionality - Feasibility Check:
- Traverse the houses sequentially and greedily select houses to rob as long as the amount in the house (
nums[i]
) is ≤cap
. - If the robber can rob at least
k
houses in this manner, then that capability is feasible.
- Traverse the houses sequentially and greedily select houses to rob as long as the amount in the house (
- Binary Search Execution:
- Use binary search to find the minimum feasible
cap
:- Start with
low = min(nums)
(the smallest amount in any house) andhigh = max(nums)
(the largest amount in any house). - For each mid-point in the binary search, check if it’s feasible to rob
k
houses with that capability. - Narrow the search range accordingly.
- Start with
- Use binary search to find the minimum feasible
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n * log(max(nums)))
- Binary search runs in
O(log(max(nums)))
. - Feasibility check performed in each binary search step costs
O(n)
. - Total time complexity:
O(n * log(max(nums)))
.
- Binary search runs in
- 🧺 Space complexity:
O(1)
since no additional data structures are used.