Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created March 15, 2025 16:09
Show Gist options
  • Save tatsuyax25/86499f22d8d22ceafc1cb613f0ebee27 to your computer and use it in GitHub Desktop.
Save tatsuyax25/86499f22d8d22ceafc1cb613f0ebee27 to your computer and use it in GitHub Desktop.
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 amoun
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var minCapability = function(nums, k) {
// Define the binary search range: minimum and maximum house values.
let left = Math.min(...nums), right = Math.max(...nums);
// Function to check if a given capability can rob at least `k` house.
const canRob = (cap) => {
let count = 0; // Number of houses robbed.
let i = 0; // Pointer to traverse house.
while (i < nums.length) {
if (nums[i] <= cap) {
// Rob the house if its value is within the capability.
count++;
i++; // Skip the next house (no adjacent robbing).
}
i++; // Movde to the next house.
}
// Return true if we can rob at least `k` houses.
return count >= k;
};
// Binary search to minimize the capability.
while (left < right) {
const mid = Math.floor((left + right) / 2); // Midpoint of current range.
if (canRob(mid)) {
// If it's feasible with this capability, try for a smaller one.
right = mid;
} else {
// Otherwise, increase the capability
left = mid + 1;
}
}
// Left pointer now represents the minimum feasible capability.
return left;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment