LeetCode in Kotlin

3840. House Robber V

Medium

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed and is protected by a security system with a color code.

You are given two integer arrays nums and colors, both of length n, where nums[i] is the amount of money in the ith house and colors[i] is the color code of that house.

You cannot rob two adjacent houses if they share the same color code.

Return the maximum amount of money you can rob.

Example 1:

Input: nums = [1,4,3,5], colors = [1,1,2,2]

Output: 9

Explanation:

Example 2:

Input: nums = [3,1,2,4], colors = [2,3,2,2]

Output: 8

Explanation:

Example 3:

Input: nums = [10,1,3,9], colors = [1,1,1,2]

Output: 22

Explanation:

Constraints:

Solution

import kotlin.math.max

class Solution {
    fun rob(nums: IntArray, colors: IntArray): Long {
        val n = nums.size
        var dp0: Long = 0
        var dp1 = nums[0].toLong()
        for (i in 1..<n) {
            val new0: Long
            val new1: Long
            if (colors[i] == colors[i - 1]) {
                new1 = dp0 + nums[i]
                new0 = max(dp0, dp1)
            } else {
                new0 = max(dp1, dp0)
                new1 = max(dp0, dp1) + nums[i]
            }
            dp0 = new0
            dp1 = new1
        }
        return max(dp0, dp1)
    }
}