[LeetCode] House Robber IV

2560. House Robber IV

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
bool helper(vector<int>& A, int k, long long m) {
int now = 0;
for(int i = 0; i < A.size(); i++) {
if(A[i] <= m) i += 1, now += 1;
}
return now >= k;
}
public:
int minCapability(vector<int>& A, int k) {
long long l = 0, r = INT_MAX, res = INT_MAX;
while(l <= r) {
long long m = l + (r - l) / 2;
bool ok = helper(A,k,m);
if(ok) {
res = min(res, m);
r = m - 1;
} else l = m + 1;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/02/06/PS/LeetCode/house-robber-iv/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.