#2560

House Robber IV

Medium
ArrayBinary SearchDynamic ProgrammingGreedyBinary SearchGreedyDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log m)
Space
O(1)
O(1)
💡

Intuition

Time O(n log m)Space O(1)

The optimal solution utilizes binary search combined with a greedy approach to efficiently find the minimum capability. By searching for the minimum possible maximum value that allows robbing at least k houses, we reduce the problem size significantly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize low as the minimum value in nums and high as the maximum value.
  2. 2Step 2: Perform binary search while low is less than high: - Calculate mid as the average of low and high. - Check if it's possible to rob at least k houses with the maximum capability of mid. - If possible, update high to mid; otherwise, update low to mid + 1.
  3. 3Step 3: Return low as the minimum capability.
solution.py18 lines
1def canRob(nums, k, max_cap):
2    count = 0
3    prev_index = -2
4    for i in range(len(nums)):
5        if nums[i] <= max_cap and i - prev_index > 1:
6            count += 1
7            prev_index = i
8    return count >= k
9
10def minCapability(nums, k):
11    low, high = min(nums), max(nums)
12    while low < high:
13        mid = (low + high) // 2
14        if canRob(nums, k, mid):
15            high = mid
16        else:
17            low = mid + 1
18    return low

Complexity note: The time complexity is O(n log m) where n is the number of houses and m is the range of money values. We perform binary search on the money values while checking each value against the houses in linear time.

  • 1Binary search can efficiently narrow down the search space for the minimum capability.
  • 2Greedy checks ensure that we can rob the required number of houses without violating adjacency rules.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.