House Robber IV — LeetCode 2560 Python Solution
- Problem
- #2560
- Pattern
- Monotonic Stack
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- nums = [2,3,5,9], k = 2
- Output
- 5
- Explanation
- There are three ways to rob at least 2 houses:
Python solution
class Solution:
def minCapability(self, nums: List[int], k: int) -> int:
def f(x):
cnt, j = 0, -2
for i, v in enumerate(nums):
if v > x or i == j + 1:
continue
cnt += 1
j = i
return cnt >= k
return bisect_left(range(max(nums) + 1), True, key=f)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log m) |
| Space | O(1) auxiliary |
Pattern: Monotonic Stack
Answer "what is the next greater element" for every position in one pass. LeetCode 2560. House Robber IV is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2560. House Robber IV?
- LeetCode 2560. House Robber IV is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2560. House Robber IV?
- The Python solution on this page runs in O(n \times \log m).
- What is the space complexity of LeetCode 2560. House Robber IV?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2560. House Robber IV cover?
- LeetCode 2560. House Robber IV is tagged Greedy, Array, Binary Search and Dynamic Programming on LeetCode.