<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 {
    int kadane(vector<int> nums, int k){//KADANES ALGO FOR LARGEST SUM NOT GREATER THAN K
        int currsum=0,maxsum=INT_MIN;
        set<int> set1;
        set1.insert(0);

        for(int i=0;i<nums.size();i++){//eg:{-2, -3, 11}
            currsum+= nums[i];
            set<int> :: iterator it = set1.lower_bound(currsum - k);//sorted set so bin search apply frm lowest elem to find any elem>=curr-k so that when we remove it frm curr, curr - (curr-k)or more = k or less than k--> then maxsum will store the largest of these near k numbers
            if(it != set1.end())//for 3rd elem, well find ((-2-3+11 = 6)-8) = -2 in set as the sum of nums(0 to 0)
                maxsum = max(maxsum, currsum - *it);//currsum(nums[2 to 0]) - -2(nums[0 to 0]) = 8, ie, nums[2 to 1] is equal to k(best case)
            set1.insert(currsum);
        }
        return maxsum;
    }
public:
    int maxSumSubmatrix(vector<vector<int>>& matrix, int k) {

        int R=matrix.size(), C=matrix[0].size(), currsum,maxsum=INT_MIN;
        vector<int> sumcols_start_to_end(R);
        
        for(int colstart=0; colstart<C;colstart++){
            for( int i=0;i<R;i++)
                sumcols_start_to_end[i] = 0;
            for(int colend=colstart;colend<C;colend++){
                for(int row=0; row<R; row++){
                    sumcols_start_to_end[row] += matrix[row][colend];
                }
                currsum = kadane(sumcols_start_to_end, k);
                maxsum = max(maxsum, currsum);
            }
        }
        return maxsum;  
    }
};
257158