Advertisement
SalmaYasser

Untitled

Jan 17th, 2020
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.89 KB | None | 0 0
  1. class Solution {
  2. public:
  3. inline int valid (int r , int c, vector<vector<int>> &grid)
  4. {
  5. return r < grid.size() && c < grid[0].size() ? grid[r][c] : 0;
  6. }
  7. inline int get_sum (int row1, int col1, int row2, int col2, vector<vector<int>> &grid)
  8. {
  9. return valid(row2, col2,grid) - valid(row1 - 1, col2,grid) - valid(row2 , col1 - 1,grid) + valid (row1 -1, col1 -1,grid);
  10. }
  11.  
  12.  
  13.  
  14. int maxSumSubmatrix(vector<vector<int>>& matrix, int k) {
  15.  
  16. vector <int> cur_col;
  17. vector<vector<int>> grid = matrix;
  18.  
  19. int rows = matrix.size();
  20. int cols = matrix[0].size();
  21.  
  22. for (int i = 0 ; i< rows ; i ++ )
  23. for (int j = 0 ; j < cols ; j ++)
  24. grid[i][j] += valid (i-1, j,grid) + valid(i,j-1,grid) - valid(i-1,j-1,grid);
  25.  
  26. int res = INT_MIN;
  27. for (int top_left_y = 0 ; top_left_y < rows ; top_left_y++)
  28. {
  29. for (int top_left_x = 0 ; top_left_x < cols; top_left_x++)
  30. {
  31. for ( int bottom_right_y = top_left_y ; bottom_right_y < rows ; bottom_right_y++ )
  32. {
  33. for (int bottom_right_x = top_left_x ; bottom_right_x < cols; bottom_right_x++)
  34. {
  35.  
  36. int cur_sum = get_sum (top_left_y, top_left_x, bottom_right_y, bottom_right_x,grid);
  37.  
  38. if (cur_sum > k)
  39. continue;
  40. res = max(res, cur_sum);
  41. }
  42. }
  43. }
  44.  
  45. }
  46.  
  47.  
  48. return res;
  49. }
  50. };
  51. /*
  52.  
  53.  
  54. */
  55. int maxSumSubmatrix(vector<vector<int>>& matrix, int k) {
  56.  
  57. int rows = matrix.size();
  58. int cols = matrix[0].size();
  59.  
  60. for (int i = 0 ; i< rows ; i ++ )
  61. for (int j = 1 ; j < cols ; j ++)
  62. matrix[i][j] += matrix[i][j-1];
  63.  
  64. int res = INT_MIN;
  65. for (int top_left_x = 0 ; top_left_x < cols; top_left_x++)
  66. for (int bottom_right_x = top_left_x ; bottom_right_x < cols; bottom_right_x++) {
  67. vector<int> x(rows);
  68. for(int r = 0; r < rows; r++) {
  69. x[r] = matrix[r][bottom_right_x] - (top_left_x == 0? 0 : matrix[r][top_left_x-1]);
  70. }
  71. int cur_sum = 0;
  72. set<int> prevSums;
  73. prevSums.insert(0);
  74. for(int r = 0; r < rows; r++) {
  75. cur_sum += x[r];
  76. int req = cur_sum - k;
  77. auto it = prevSums.lower_bound(req);
  78. if(it != prevSums.end()){
  79. res = max(res, cur_sum - *it);
  80. }
  81. prevSums.insert(cur_sum);
  82. }
  83. }
  84.  
  85.  
  86. return res;
  87. }
  88. };
  89. /*
  90.  
  91.  
  92. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement