<p>Given an <code>m x n</code> matrix <code>matrix</code> and an integer <code>k</code>, return <em>the max sum of a rectangle in the matrix such that its sum is no larger than</em> <code>k</code>.</p>

<p>It is <strong>guaranteed</strong> that there will be a rectangle with a sum no larger than <code>k</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/03/18/sum-grid.jpg" style="width: 255px; height: 176px;" />
<pre>
<strong>Input:</strong> matrix = [[1,0,1],[0,-2,3]], k = 2
<strong>Output:</strong> 2
<strong>Explanation:</strong> Because the sum of the blue rectangle [[0, 1], [-2, 3]] is 2, and 2 is the max number no larger than k (k = 2).
</pre>

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

<pre>
<strong>Input:</strong> matrix = [[2,2,-1]], k = 3
<strong>Output:</strong> 3
</pre>

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

<ul>
	<li><code>m == matrix.length</code></li>
	<li><code>n == matrix[i].length</code></li>
	<li><code>1 &lt;= m, n &lt;= 100</code></li>
	<li><code>-100 &lt;= matrix[i][j] &lt;= 100</code></li>
	<li><code>-10<sup>5</sup> &lt;= k &lt;= 10<sup>5</sup></code></li>
</ul>

<p>&nbsp;</p>
<p><strong>Follow up:</strong> What if the number of rows is much larger than the number of columns?</p>

class Solution {
public:

    int maxSumSubmatrix(vector<vector<int>>& matrix, int k) {

        int n = matrix.size();
        int m = matrix[0].size();

        vector<vector<int>>mat_m(n,vector<int>(m+1,0));
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                mat_m[i][j+1]=mat_m[i][j] + matrix[i][j];
            }
        }

        vector<vector<vector<int>>>wind_col_pref(m+1,vector<vector<int>>(m+1,vector<int>(n+1,0)));
        for(int c1=1;c1<=m;c1++){
            for(int c2=c1;c2<=m;c2++){
                wind_col_pref[c1][c2][0]=0;
                for(int i=0;i<n;i++){
                    wind_col_pref[c1][c2][i+1] = wind_col_pref[c1][c2][i] + (mat_m[i][c2]-mat_m[i][c1-1]);
                }
            }
        }
        
        int maxi = -INT_MAX;

        for(int c1=1;c1<=m;c1++){
            for(int c2 = c1;c2<=m;c2++){

                for(int r1=1;r1<=n;r1++){
                    for(int r2=r1;r2<=n;r2++){

                        int val = wind_col_pref[c1][c2][r2]-wind_col_pref[c1][c2][r1-1];
                        if(val<=k && val>maxi) maxi = val;

                    }
                }
            }
        }

        return maxi;

    }
};
19709