Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created March 15, 2025 22:01
Show Gist options
  • Save Ifihan/0c39c142caf05179a3b933a8b14f2f0f to your computer and use it in GitHub Desktop.
Save Ifihan/0c39c142caf05179a3b933a8b14f2f0f to your computer and use it in GitHub Desktop.
House Robber IV

Question

Approach

For this question, I used a binary search approach to determine the minimum capability the robber needs. The search space is between the smallest and largest house values.

The helper function canRob(capability) checks if it's possible to rob at least k houses without stealing from adjacent ones.

Implementation

class Solution:
    def minCapability(self, nums: List[int], k: int) -> int:
        left, right = min(nums), max(nums)
        
        def canRob(capability: int) -> bool:
            count, i = 0, 0
            while i < len(nums):
                if nums[i] <= capability:
                    count += 1
                    i += 1
                i += 1
            return count >= k
        
        while left < right:
            mid = (left + right) // 2
            if canRob(mid):
                right = mid
            else:
                left = mid + 1
        
        return left

Complexities

  • Time: O(n log max(nums))
  • Space: O(1)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment