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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,7,11,15], k = 1
Output: 2
💡 Note: We can rob house 0 alone with capability 2, which is the minimum possible
Example 2 — Multiple Houses Required
$ Input: nums = [2,3,5,9], k = 2
Output: 5
💡 Note: Rob houses [2,5] with capability max(2,5)=5, or houses [3,9] with capability max(3,9)=9. Minimum is 5
Example 3 — Edge Case
$ Input: nums = [1,2,3], k = 1
Output: 1
💡 Note: Rob only house 0 with value 1, giving capability 1

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109
  • 1 ≤ k ≤ (nums.length + 1) / 2

Visualization

Tap to expand
House Robber IV - Greedy Approach INPUT $2 $7 $11 $15 nums = [2, 7, 11, 15] 2 7 11 15 idx: 0 1 2 3 k = 1 (min houses) ALGORITHM STEPS 1 Binary Search Setup Range: [min(nums), max(nums)] lo=2, hi=15 2 Greedy Check For mid capability, count max non-adjacent houses 3 Try mid=8 Houses with val <= 8: [2,7] Can rob house 0 (val=2) 4 Narrow Search If count >= k: hi = mid Else: lo = mid + 1 lo=2 mid=8 hi=15 lo=2 mid=5 hi=8 lo=2 mid=3 hi=5 --> 2 FINAL RESULT $2 Robber Minimum Capability 2 Rob house 0 with $2 Satisfies k=1 requirement Max stolen from single house = 2 (minimum possible) OK Key Insight: Binary search on the answer (capability). For each candidate capability value, use greedy to count maximum non-adjacent houses that can be robbed. If we can rob >= k houses, the capability is achievable. Search for the minimum such capability in O(n log m) time. TutorialsPoint - House Robber IV | Greedy + Binary Search Approach
Asked in
Google 12 Facebook 8 Amazon 15 Microsoft 10
23.4K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen