⚡Flashcard Drill➔
NeetCode #279LC-2560MediumBinary Search
← Back to All Problems

#279 · #2560 · House Robber IV(打家劫舍 IV)

📌 Problem Statement & Constraints

You are given an integer array nums and an integer k. You must rob at least k houses; adjacent houses cannot both be robbed. The capability is the maximum amount robbed from any single house. Return the minimum possible capability. Constraints: 1 <= nums.length <= 10^5, 1 <= nums[i] <= 10^9, 1 <= k <= (nums.length + 1) / 2.

💡 Core Algorithmic Approaches

  1. Binary search on the capability c: "can we rob at least k houses using only houses with nums[i] <= c" is monotone.
  2. The greedy for a given c is to scan left to right and rob any eligible house, skipping the next one -- this maximises the count.
  3. The eligibility is nums[i] <= c, and adjacency is handled by jumping two steps after a robbery.
  4. The lower bound is min(nums) and the upper bound max(nums), since k is guaranteed achievable.

💻 Benchmark Python3 Implementation

class Solution:
    def minCapability(self, nums: List[int], k: int) -> int:
        lo, hi = min(nums), max(nums)
        while lo < hi:
            mid = (lo + hi) // 2
            # greedily count how many non-adjacent houses have value <= mid
            cnt = 0
            i = 0
            while i < len(nums):
                if nums[i] <= mid:
                    cnt += 1
                    i += 2             # cannot rob the neighbour
                else:
                    i += 1
            if cnt >= k:
                hi = mid               # feasible -> try a lower capability
            else:
                lo = mid + 1
        return lo

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n log(max(nums))): each greedy pass is O(n).
💾 Space Complexity
O(1): a few scalars.

⚠️ Interview Pitfalls & Follow-ups

  • Using DP to count the maximum robberies: O(n) per check, which is the same, but the greedy is simpler and provably optimal for counting.
  • Jumping only one step after robbing: the next house cannot be robbed, so the jump is two.
  • Setting the lower bound to 0: a capability below min(nums) can never rob even one house, so min(nums) is tight.
  • Using hi = mid - 1 when feasible: could skip the optimum.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Binary Search Problems

中文速览与面试要点

打家劫舍 IV

沿街有一排连续的房屋。每间房屋内都藏有一定的现金。现在有一位小偷计划从这些房屋中窃取现金。由于相邻的房屋装有相互连通的防盗系统,所以小偷 不会 窃取相邻的房屋。小偷的 窃取能力 定义为他在窃取过程中能从单间房屋中窃取的最大金额。给你一个整数数组 nums 表示每间房屋存放的现金金额,以及一个整数 k。请你返回小偷窃取 至少 k 间房屋所需要的 最小窃取能力 。约束:1 ≤ nums.length ≤ 10^5;1 ≤ nums[i] ≤ 10^9;1 ≤ k ≤ (nums.length + 1) / 2。

核心要点

  • 二分窃取能力 + 贪心判定(标准解) :二分「窃取能力 cap」,判定「在只能偷金额 ≤ cap 的房屋、且不偷相邻房屋的前提下,最多能偷多少间」。
  • 判定函数(贪心) :从左到右遍历,若当前房屋金额 ≤ cap,则偷它并跳过下一间( i += 2 );否则跳过( i += 1 )。统计偷的数量。
  • 为什么贪心正确 :能偷就偷、偷完跳过下一间,是「不相邻选择」的经典贪心,可以得到最大数量。
  • 答案范围 : [min(nums), max(nums)] 。
  • 单调性 :cap 越大,可偷的房屋越多,因此可以二分(求最小值)。

常见陷阱

  • 判定函数用 DP 求最大独立集 :DP 需要 O(n) 空间且更复杂;本题的贪心(能偷就偷、跳下一间)已是最优,O(1) 空间。
  • 判定时只统计金额 ≤ cap 的房屋总数 :忽略了「不能相邻」的约束,会高估可偷数量。
  • i += 2 写成 i += 1 :会导致相邻房屋都被选中,违反约束。
  • 二分方向写反 :本题求「最小能力」,应写 if feasible: r = mid 。
  • 下界写成 0 :nums[i] ≥ 1,下界取 min(nums) 更紧。

参考实现

class Solution:
    def minCapability(self, nums: list[int], k: int) -> int:
        def max_houses(cap: int) -> int:
            """在能力上限为 cap 时,最多能偷多少间(不能相邻)。"""
            cnt = 0
            i = 0
            n = len(nums)
            while i < n:
                if nums[i] <= cap:
                    cnt += 1
                    i += 2              # 偷了这间,跳过下一间
                else:
                    i += 1
            return cnt

        l, r = min(nums), max(nums)
        while l < r:
            mid = (l + r) // 2
            if max_houses(mid) >= k:
                r = mid                 # 可行 -> 尝试更小的能力
            else:
                l = mid + 1
        return l