LeetCode2560. House Robber IV——二分答案+动态规划

文章讨论了一个问题,给定一组房子的金钱数额和最小偷窃房屋数,目标是找到抢劫者所需的最小抢劫能力。解决方案使用了动态规划来确定在满足至少偷窃k个房子的情况下,抢劫者可以从哪些组合中获得最小的最大金额。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、题目

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.

Example 1:

Input: nums = [2,3,5,9], k = 2
Output: 5
Explanation:
There are three ways to rob at least 2 houses:

  • Rob the houses at indices 0 and 2. Capability is max(nums[0], nums[2]) = 5.
  • Rob the houses at indices 0 and 3. Capability is max(nums[0], nums[3]) = 9.
  • Rob the houses at indices 1 and 3. Capability is max(nums[1], nums[3]) = 9.
    Therefore, we return min(5, 9, 9) = 5.
    Example 2:

Input: nums = [2,7,9,3,1], k = 2
Output: 2
Explanation: There are 7 ways to rob the houses. The way which leads to minimum capability is to rob the house at index 0 and 4. Return max(nums[0], nums[4]) = 2.

Constraints:

1 <= nums.length <= 105
1 <= nums[i] <= 109
1 <= k <= (nums.length + 1)/2

二、题解

class Solution {
public:
    int minCapability(vector<int>& nums, int k) {
        int n = nums.size();
        int l = *min_element(nums.begin(),nums.end());
        int r = *max_element(nums.begin(),nums.end());
        int res = 0;
        while(l <= r){
            int mid = (l + r) / 2;
            if(check(nums,n,mid) >= k){
                res = mid;
                r = mid - 1;
            }
            else l = mid + 1;
        }
        return res;
    }
    int check(vector<int>& nums,int n,int ability){
        if(n == 1) return nums[0] <= ability ? 1 : 0;
        if(n == 2) return (nums[0] <= ability || nums[1] <= ability) ? 1 : 0;
        vector<int> dp(n,0);
        dp[0] = nums[0] <= ability ? 1 : 0;
        dp[1] = (nums[0] <= ability || nums[1] <= ability) ? 1 : 0;
        for(int i = 2;i < n;i++){
            dp[i] = max(dp[i-1],(nums[i] <= ability ? 1 : 0) + dp[i-2]);
        }
        return dp[n-1];
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值