<p>You are given a 2D <strong>binary</strong> array <code>grid</code>. You need to find 3 <strong>non-overlapping</strong> rectangles having <strong>non-zero</strong> areas with horizontal and vertical sides such that all the 1&#39;s in <code>grid</code> lie inside these rectangles.</p>

<p>Return the <strong>minimum</strong> possible sum of the area of these rectangles.</p>

<p><strong>Note</strong> that the rectangles are allowed to touch.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[1,0,1],[1,1,1]]</span></p>

<p><strong>Output:</strong> <span class="example-io">5</span></p>

<p><strong>Explanation:</strong></p>

<p><img alt="" src="https://assets.leetcode.com/uploads/2024/05/14/example0rect21.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 280px; height: 198px;" /></p>

<ul>
	<li>The 1&#39;s at <code>(0, 0)</code> and <code>(1, 0)</code> are covered by a rectangle of area 2.</li>
	<li>The 1&#39;s at <code>(0, 2)</code> and <code>(1, 2)</code> are covered by a rectangle of area 2.</li>
	<li>The 1 at <code>(1, 1)</code> is covered by a rectangle of area 1.</li>
</ul>
</div>

<p><strong class="example">Example 2:</strong></p>

<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[1,0,1,0],[0,1,0,1]]</span></p>

<p><strong>Output:</strong> <span class="example-io">5</span></p>

<p><strong>Explanation:</strong></p>

<p><img alt="" src="https://assets.leetcode.com/uploads/2024/05/14/example1rect2.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 356px; height: 198px;" /></p>

<ul>
	<li>The 1&#39;s at <code>(0, 0)</code> and <code>(0, 2)</code> are covered by a rectangle of area 3.</li>
	<li>The 1 at <code>(1, 1)</code> is covered by a rectangle of area 1.</li>
	<li>The 1 at <code>(1, 3)</code> is covered by a rectangle of area 1.</li>
</ul>
</div>

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

<ul>
	<li><code>1 &lt;= grid.length, grid[i].length &lt;= 30</code></li>
	<li><code>grid[i][j]</code> is either 0 or 1.</li>
	<li>The input is generated such that there are at least three 1&#39;s in <code>grid</code>.</li>
</ul>

class Solution:
    def minimumSum(self, grid: List[List[int]]) -> int:
        m,n = len(grid),len(grid[0])
        oo = m*n+1
        def rect(g): # min rect, ensure existing 1
            up = 0
            while g[up].count(1)==0: up += 1
            low = len(g)-1
            while g[low].count(1)==0: low -= 1
            left = -1
            for i,col in enumerate(zip(*g)):
                if col.count(1)!=0:
                    if left==-1: left = i
                    right = i
            return (low-up+1)*(right-left+1)
        def hor2(g): # min area of 2 horizontal
            icol = []
            for i,col in enumerate(zip(*g)):
                if col.count(1): icol.append(i)
            if len(icol)<2: return oo
            best = oo
            for i in range(len(icol)-1): #
                w1 = icol[i]-icol[0]+1
                up = 0
                while g[up][:icol[i]+1].count(1)==0: up += 1
                low = len(g)-1
                while g[low][:icol[i]+1].count(1)==0: low -= 1
                area = w1*(low-up+1)
                w2 = icol[-1]-icol[i+1]+1
                up = 0
                while g[up][icol[i+1]:].count(1)==0: up += 1
                low = len(g)-1
                while g[low][icol[i+1]:].count(1)==0: low -= 1
                area += w2*(low-up+1)
                best = min(best,area)
            #
            return best

        def minarea(g):
            irow = []
            for i,row in enumerate(g):
                if row.count(1): irow.append(i)
            # three h 0~r1, r1+1 ~ r2, r2+1~
            best = oo; #print(irow)
            nr = len(irow)
            for r1 in range(nr-2):
                rec1 = rect(g[irow[0]:irow[r1]+1])
                for r2 in range(r1+1,nr-1):
                    rec2 = rect(g[irow[r1+1]:irow[r2]+1])
                    rec3 = rect(g[irow[r2+1]:irow[nr-1]+1])
                    best = min(best,rec1+rec2+rec3)
            #print(best)
            # type 1+2 
            for r1 in range(nr-1):
                rec1 = rect(g[irow[0]:irow[r1]+1])
                rec2 = hor2(g[irow[r1+1]:irow[nr-1]+1])
                best = min(best,rec1+rec2)
                #print('1+2:',r1,best)
                #type 2+1
                rec1 = hor2(g[irow[0]:irow[r1]+1])
                rec2 = rect(g[irow[r1+1]:irow[nr-1]+1])
                best = min(best,rec1+rec2)
                #print('2+1:',r1,best)
            return best
        #
        area = minarea(grid)
        #print(area)
        g = list(zip(*grid))
        #print(g)
        area = min(area,minarea(g))
        return area


265