2560. House Robber IV #1434
-
Topics: 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 You are also given an integer Return the minimum capability of the robber out of all the possible ways to steal at least Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine the minimum capability of a robber who steals from at least Approach
Let's implement this solution in PHP: 2560. House Robber IV <?php
/**
* @param Integer[] $nums
* @param Integer $k
* @return Integer
*/
function minCapability($nums, $k) {
$left = min($nums);
$right = max($nums);
$ans = $right;
while ($left <= $right) {
$mid = (int)(($left + $right) / 2);
if (isPossible($mid, $nums, $k)) {
$ans = $mid;
$right = $mid - 1;
} else {
$left = $mid + 1;
}
}
return $ans;
}
/**
* @param $mid
* @param $nums
* @param $k
* @return bool
*/
function isPossible($mid, $nums, $k) {
$count = 0;
$prev = -2; // Initialize to an index that allows the first house (0) to be considered
foreach ($nums as $i => $num) {
if ($num <= $mid && $i > $prev + 1) {
$count++;
$prev = $i;
if ($count >= $k) {
return true;
}
}
}
return $count >= $k;
}
// Example test cases
echo minCapability([2, 3, 5, 9], 2) . "\n"; // Output: 5
echo minCapability([2, 7, 9, 3, 1], 2) . "\n"; // Output: 2
?> Explanation:
This approach efficiently narrows down the minimum capability using binary search combined with a linear-time check, ensuring optimal performance even for large input sizes. |
Beta Was this translation helpful? Give feedback.
We need to determine the minimum capability of a robber who steals from at least
k
non-consecutive houses, where the capability is defined as the maximum amount stolen from any single house. The solution involves using binary search to efficiently find the minimum possible capability.Approach
k
non-consecutive houses where each stolen amount is less than or equal to the midpoint value. This check i…