LeetCode in Kotlin

2560. House Robber IV

Medium

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:

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:

Solution

class Solution {
    fun minCapability(nums: IntArray, k: Int): Int {
        var l = 1
        var r = 1e9.toInt()
        while (l < r) {
            val mid = l + (r - l) / 2
            if (isPossible(nums, mid, k)) {
                r = mid
            } else {
                l = mid + 1
            }
        }
        return r
    }

    private fun isPossible(nums: IntArray, maxMoney: Int, k: Int): Boolean {
        var houseStolen = 0
        var lastStolenIdx = -2
        for (i in nums.indices) {
            if (nums[i] > maxMoney) {
                continue
            }
            if (i == lastStolenIdx + 1) {
                continue
            }
            houseStolen++
            lastStolenIdx = i
        }
        return houseStolen >= k
    }
}