LeetCode in Kotlin

2312. Selling Pieces of Wood

Hard

You are given two integers m and n that represent the height and width of a rectangular piece of wood. You are also given a 2D integer array prices, where prices[i] = [hi, wi, pricei] indicates you can sell a rectangular piece of wood of height hi and width wi for pricei dollars.

To cut a piece of wood, you must make a vertical or horizontal cut across the entire height or width of the piece to split it into two smaller pieces. After cutting a piece of wood into some number of smaller pieces, you can sell pieces according to prices. You may sell multiple pieces of the same shape, and you do not have to sell all the shapes. The grain of the wood makes a difference, so you cannot rotate a piece to swap its height and width.

Return the maximum money you can earn after cutting an m x n piece of wood.

Note that you can cut the piece of wood as many times as you want.

Example 1:

Input: m = 3, n = 5, prices = [[1,4,2],[2,2,7],[2,1,3]]

Output: 19

Explanation: The diagram above shows a possible scenario. It consists of:

This obtains a total of 14 + 3 + 2 = 19 money earned.

It can be shown that 19 is the maximum amount of money that can be earned.

Example 2:

Input: m = 4, n = 6, prices = [[3,2,10],[1,4,2],[4,1,3]]

Output: 32

Explanation: The diagram above shows a possible scenario. It consists of:

This obtains a total of 30 + 2 = 32 money earned.

It can be shown that 32 is the maximum amount of money that can be earned.

Notice that we cannot rotate the 1 x 4 piece of wood to obtain a 4 x 1 piece of wood.

Constraints:

Solution

class Solution {
    fun sellingWood(m: Int, n: Int, prices: Array<IntArray>): Long {
        // dp[i][j] = Maximum profit selling wood of size i*j
        val dp = Array(m) { LongArray(n) }
        for (price in prices) {
            dp[price[0] - 1][price[1] - 1] = dp[price[0] - 1][price[1] - 1].coerceAtLeast(price[2].toLong())
        }
        for (i in 0 until m) {
            for (j in 0 until n) {
                // Cut Vertically
                for (k in 0 until j) {
                    dp[i][j] = dp[i][j].coerceAtLeast(dp[i][k] + dp[i][j - k - 1])
                }
                // Cut Horizontally
                for (k in 0 until i) {
                    dp[i][j] = dp[i][j].coerceAtLeast(dp[k][j] + dp[i - k - 1][j])
                }
            }
        }
        return dp[m - 1][n - 1]
    }
}