【力扣-每日一题】2560. 打家劫舍 IV

cpp 复制代码
class Solution {
public:
    bool check(vector<int> &nums,int max_num,int k)
    {
        //只需要计算可以偷的房间。在满足最大值为max_num下时,能偷的最多的房间,与k值比较
        //如果大于K,说明max_num还可以缩小
        //如果小于看,说明max_num需要放大
        int count=0;
        for(int i=0;i<nums.size();i++)
        {
            if(nums[i]<=max_num){
                count++;    //计数
                i++;    //下一个不能偷
            }
        }
        return count>=k;
    }
    int minCapability(vector<int>& nums, int k) {
        //在满足偷k个房间的所有情况下,找出最小的窃取能力。每种情况中房屋金额最大值,为该情况的窃取能力
        //目标:所有情况中最小的窃取能力
    //二分答案
    int left=0,right=*max_element(nums.begin(),nums.end());
    while(left+1<right)   //开
    {
        int mid=(left+right)/2;
        if(check(nums,mid,k))
            //能整好偷,或偷的个数要多,需要减小最大值
            right=mid;
        else left=mid;

    }
        return right;
    }
};
相关推荐
蛋蛋的就会顺顺的6 小时前
hot100——矩阵
java·数据结构·算法·leetcode·力扣
想吃火锅100510 小时前
【leetcode】238.除了自身以外数组的乘积js
javascript·算法·leetcode
Tisfy12 小时前
LeetCode 0020.有效的括号:栈匹配
算法·leetcode·字符串·题解·括号匹配
Navigator_Z12 小时前
LeetCode //C - 1276. Number of Burgers with No Waste of Ingredients
c语言·算法·leetcode
想吃火锅100513 小时前
【leetcode】189.轮转数组js
开发语言·javascript·leetcode
All for pursuit.14 小时前
【贪心-2】253.会议室 II
数据结构·c++·算法·leetcode
All for pursuit.1 天前
【分治-3】347.前K个高频元素
数据结构·c++·算法·leetcode
All for pursuit.1 天前
【二分查找-2】34.在排序数组中查找元素的第一个和最后一个位置
数据结构·c++·算法·leetcode
blxr_1 天前
力扣hot100爬楼梯https://leetcode.cn/problems/climbing-stairs/
算法·leetcode·职场和发展
Navigator_Z1 天前
LeetCode //C - 1275. Find Winner on a Tic Tac Toe Game
c语言·算法·leetcode