Skip to content

Commit cb0f6c6

Browse files
committed
Runtime: 1989 ms (Top 31.75%) | Memory: 238.4 MB (Top 54.28%)
1 parent eafd9f5 commit cb0f6c6

File tree

1 file changed

+34
-33
lines changed

1 file changed

+34
-33
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,84 +1,85 @@
1+
// Runtime: 1989 ms (Top 31.75%) | Memory: 238.4 MB (Top 54.28%)
12
class Solution {
23
public:
3-
4+
45
// function for finding maximum subarray having sum less than k
5-
6+
67
int find_max(vector<int>& arr, int k)
78
{
89
int n = arr.size();
9-
10+
1011
int maxi = INT_MIN;
11-
12+
1213
// curr_sum will store cumulative sum
13-
14+
1415
int curr_sum = 0;
15-
16+
1617
// set will store the prefix sum of array
17-
18+
1819
set<int> s;
19-
20-
// put 0 into set, if curr_sum == k, (curr_sum - k) will be zero
21-
20+
21+
// put 0 into set, if curr_sum == k, (curr_sum - k) will be zero
22+
2223
s.insert(0);
23-
24+
2425
for(int i = 0; i < n; i++)
2526
{
2627
// calculate cumulative sum
27-
28+
2829
curr_sum += arr[i];
29-
30+
3031
// find the prefix sum in set having sum == curr_sum - k
31-
32+
3233
auto it = s.lower_bound(curr_sum - k);
33-
34+
3435
// if prefix sum is present, update the maxi
35-
36+
3637
if(it != s.end())
3738
{
3839
maxi = max(maxi, curr_sum - *it);
3940
}
40-
41+
4142
// insert prefix sum into set
42-
43+
4344
s.insert(curr_sum);
4445
}
45-
46+
4647
return maxi;
4748
}
48-
49+
4950
int maxSumSubmatrix(vector<vector<int>>& matrix, int k) {
50-
51+
5152
int n = matrix.size();
52-
53+
5354
int m = matrix[0].size();
54-
55+
5556
int maxi = INT_MIN;
56-
57+
5758
// fix the position two two rows and take cumulative sum of columns between two fixed rows
58-
59+
5960
for(int start_row = 0; start_row < n; start_row++)
6061
{
6162
vector<int> col_array(m, 0);
62-
63+
6364
for(int end_row = start_row; end_row < n; end_row++)
6465
{
6566
// take cumulative sum of columns between two fixed rows
66-
67+
6768
for(int col = 0; col < m; col++)
6869
{
6970
col_array[col] += matrix[end_row][col];
7071
}
71-
72+
7273
// find maximum subarray having sum less than equal to k
73-
74+
7475
int curr_max = find_max(col_array, k);
75-
76+
7677
// update the maximum sum
77-
78+
7879
maxi = max(maxi, curr_max);
7980
}
8081
}
81-
82+
8283
return maxi;
8384
}
84-
};
85+
};

0 commit comments

Comments
 (0)