IT评测·应用市场-qidao123.com

标题: LeetCode //C - 363. Max Sum of Rectangle No Larger Than K [打印本页]

作者: 半亩花草    时间: 2024-9-13 07:02
标题: LeetCode //C - 363. Max Sum of Rectangle No Larger Than K
363. Max Sum of Rectangle No Larger Than K

Given an m x n matrix matrix and an integer k, return the max sum of a rectangle in the matrix such that its sum is no larger than k.
It is guaranteed that there will be a rectangle with a sum no larger than k.
 
Example 1:


   Input: matrix = [[1,0,1],[0,-2,3]], k = 2
Output: 2
Explanation: 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).
  Example 2:

   Input: matrix = [[2,2,-1]], k = 3
Output: 3
  Constraints:


From: LeetCode
Link: 363. Max Sum of Rectangle No Larger Than K

Solution:

Ideas:


Code:

  1. int maxSumSubmatrix(int** matrix, int matrixSize, int* matrixColSize, int k) {
  2.     int maxSum = INT_MIN;
  3.     int rows = matrixSize, cols = *matrixColSize;
  4.     // Loop through the possible row start points
  5.     for (int startRow = 0; startRow < rows; ++startRow) {
  6.         // Temporary array to store column sums
  7.         int* colSums = (int*)calloc(cols, sizeof(int));
  8.         
  9.         // Loop through the possible row end points
  10.         for (int endRow = startRow; endRow < rows; ++endRow) {
  11.             // Update column sums
  12.             for (int col = 0; col < cols; ++col) {
  13.                 colSums[col] += matrix[endRow][col];
  14.             }
  15.             // Now we need to find the subarray no larger than k in the colSums array
  16.             // Brute-force approach for subarray sums
  17.             for (int startCol = 0; startCol < cols; ++startCol) {
  18.                 int currentSum = 0;
  19.                 for (int endCol = startCol; endCol < cols; ++endCol) {
  20.                     currentSum += colSums[endCol];
  21.                     if (currentSum <= k) {
  22.                         if (currentSum > maxSum) {
  23.                             maxSum = currentSum;
  24.                         }
  25.                     }
  26.                 }
  27.             }
  28.         }
  29.         free(colSums);
  30.     }
  31.     return maxSum;
  32. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 IT评测·应用市场-qidao123.com (https://dis.qidao123.com/) Powered by Discuz! X3.4