Leetcode-2560

House Robber IV

Time complexity: $O(n\log M)$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <vector>

class Solution {
public:
    int minCapability(std::vector<int>& nums, int k) {
        int left = 0x3fff'ffff, right = 0;
        for (int n : nums) {
            left = std::min(left, n);
            right = std::max(right, n);
        }
        
        for (int mid = (left + right) / 2; right >= left; ) {
            if (check(nums, k, mid)) {
                right = mid - 1;
            }
            else {
                left = mid + 1;
            }
            mid = (right + left) / 2;
        }
        
        return left;
    }
    
private:
    bool check(std::vector<int>& nums, int k, int max_num) {
        int last = false;
        for (int n : nums) {
            if (last || n > max_num) {
                last = false;
            }
            else {
                last = true;
                --k;
                if (k == 0) {
                    return true;
                }
            }
        }
        return false;
    }
};

Leetcode-2560