<p>You are given two integers <code>m</code> and <code>n</code> that represent the height and width of a rectangular piece of wood. You are also given a 2D integer array <code>prices</code>, where <code>prices[i] = [h<sub>i</sub>, w<sub>i</sub>, price<sub>i</sub>]</code> indicates you can sell a rectangular piece of wood of height <code>h<sub>i</sub></code> and width <code>w<sub>i</sub></code> for <code>price<sub>i</sub></code> dollars.</p>

<p>To cut a piece of wood, you must make a vertical or horizontal cut across the <strong>entire</strong> 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 <code>prices</code>. 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 <strong>cannot</strong> rotate a piece to swap its height and width.</p>

<p>Return <em>the <strong>maximum</strong> money you can earn after cutting an </em><code>m x n</code><em> piece of wood</em>.</p>

<p>Note that you can cut the piece of wood as many times as you want.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2022/04/27/ex1.png" style="width: 239px; height: 150px;" />
<pre>
<strong>Input:</strong> m = 3, n = 5, prices = [[1,4,2],[2,2,7],[2,1,3]]
<strong>Output:</strong> 19
<strong>Explanation:</strong> The diagram above shows a possible scenario. It consists of:
- 2 pieces of wood shaped 2 x 2, selling for a price of 2 * 7 = 14.
- 1 piece of wood shaped 2 x 1, selling for a price of 1 * 3 = 3.
- 1 piece of wood shaped 1 x 4, selling for a price of 1 * 2 = 2.
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.
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2022/04/27/ex2new.png" style="width: 250px; height: 175px;" />
<pre>
<strong>Input:</strong> m = 4, n = 6, prices = [[3,2,10],[1,4,2],[4,1,3]]
<strong>Output:</strong> 32
<strong>Explanation:</strong> The diagram above shows a possible scenario. It consists of:
- 3 pieces of wood shaped 3 x 2, selling for a price of 3 * 10 = 30.
- 1 piece of wood shaped 1 x 4, selling for a price of 1 * 2 = 2.
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.</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= m, n &lt;= 200</code></li>
	<li><code>1 &lt;= prices.length &lt;= 2 * 10<sup>4</sup></code></li>
	<li><code>prices[i].length == 3</code></li>
	<li><code>1 &lt;= h<sub>i</sub> &lt;= m</code></li>
	<li><code>1 &lt;= w<sub>i</sub> &lt;= n</code></li>
	<li><code>1 &lt;= price<sub>i</sub> &lt;= 10<sup>6</sup></code></li>
	<li>All the shapes of wood <code>(h<sub>i</sub>, w<sub>i</sub>)</code> are pairwise <strong>distinct</strong>.</li>
</ul>



class WoodMarketOld:
    def __init__(self, prices: List[List[int]]):
        self.prices = prices

        self.cache = {}
        self.mins = [1e8, 1e8]
        for h, w, p in prices:

            if h < self.mins[0]:
                self.mins[0] = h
            if w < self.mins[1]:
                self.mins[1] = w
            
            self.cache[(h, w)] = p

        # Set all smaller pieces to 0
        for x in range(1, self.mins[0] + 1):
            for y in range(1, self.mins[1] + 1):
                if (x, y) not in self.cache:
                    self.cache[(x, y)] = 0


    def find_best_combo(self, m: int, n: int) -> int:
        
        # Check less rows
        prices = [0]
        
        if (m, n) in self.cache:
            cached_price = self.cache[(m, n)]
            return cached_price
            
            if cached_price == 0:
                return 0

            prices.append(cached_price)

        mmax = m // 2 + 1
        for m_try in range(1, mmax):
            price_row = self.find_best_combo(m_try, n)
            price_row += self.find_best_combo(m - m_try, n)
            prices.append(price_row)
        
        # Check less columns
        nmax = n // 2 + 1
        for n_try in range(1, nmax):
            price_col = self.find_best_combo(m, n_try)
            price_col += self.find_best_combo(m, n - n_try)
            prices.append(price_col)
        
        price = max(prices)
        self.cache[(m, n)] = price
        return price


def contained(size1: (int, int), size2: (int, int)) -> int:
    s1 = size1
    s2 = size2
    factor = 1
    if size1[0] < size2[0] or size1[1] < size2[1]:
        s1 = size2
        s2 = size1
        factor = -1
    
    x_amt = s1[0] // s2[0]
    y_amt = s1[1] // s2[1]

    return factor * x_amt * y_amt
    

class WoodMarket:
    def __init__(self, prices: List[List[int]]):
        self.prices = {(x, y): p for x, y, p in prices}

        sized = sorted(self.prices.keys(), key=lambda x: x[0] * x[1])
        self.cache = {}
        
        # This heuristic doesn't catch all cases, if a+b are better than c
        selected = set()
        to_remove = set()

        if sized:
            selected.add(sized.pop(0))

        for coords in sized:
            price1 = self.prices[coords]
            to_remove.clear()

            for coords2 in selected.copy():
                if coords == coords2:
                    continue

                cont = contained(coords, coords2)
                price2 = self.prices[coords2]

                if cont > 0 and price1 < cont * price2:
                    to_remove.add(coords)
                elif cont < 0 and price2 < abs(cont) * price1:
                    selected.remove(coords2)
                    to_remove.discard(coords)

            if coords not in to_remove:
                selected.add(coords)

        self.cache = {k: v for k, v in self.prices.items() if k in selected}
        print("Starting pieces:", self.cache)

        
    def find_best_combo(self, m: int, n: int) -> int:
        if (m, n) in self.cache:
            return self.cache[(m, n)]

        prices = [0]

        mmax = m // 2 + 1
        for m_try in range(1, mmax):
            price_row = self.find_best_combo(m_try, n)
            price_row += self.find_best_combo(m - m_try, n)
            prices.append(price_row)
        
        # Check less columns
        nmax = n // 2 + 1
        for n_try in range(1, nmax):
            price_col = self.find_best_combo(m, n_try)
            price_col += self.find_best_combo(m, n - n_try)
            prices.append(price_col)
        
        price = max(prices)
        self.cache[(m, n)] = price
        # print((m, n), price)
        return price


class Solution:
    def sellingWood(self, m: int, n: int, prices: List[List[int]]) -> int:
        market = WoodMarket(prices)
        price = market.find_best_combo(m, n)
        return price


4743