1
+ // Runtime: 1989 ms (Top 31.75%) | Memory: 238.4 MB (Top 54.28%)
1
2
class Solution {
2
3
public:
3
-
4
+
4
5
// function for finding maximum subarray having sum less than k
5
-
6
+
6
7
int find_max (vector<int >& arr, int k)
7
8
{
8
9
int n = arr.size ();
9
-
10
+
10
11
int maxi = INT_MIN;
11
-
12
+
12
13
// curr_sum will store cumulative sum
13
-
14
+
14
15
int curr_sum = 0 ;
15
-
16
+
16
17
// set will store the prefix sum of array
17
-
18
+
18
19
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
+
22
23
s.insert (0 );
23
-
24
+
24
25
for (int i = 0 ; i < n; i++)
25
26
{
26
27
// calculate cumulative sum
27
-
28
+
28
29
curr_sum += arr[i];
29
-
30
+
30
31
// find the prefix sum in set having sum == curr_sum - k
31
-
32
+
32
33
auto it = s.lower_bound (curr_sum - k);
33
-
34
+
34
35
// if prefix sum is present, update the maxi
35
-
36
+
36
37
if (it != s.end ())
37
38
{
38
39
maxi = max (maxi, curr_sum - *it);
39
40
}
40
-
41
+
41
42
// insert prefix sum into set
42
-
43
+
43
44
s.insert (curr_sum);
44
45
}
45
-
46
+
46
47
return maxi;
47
48
}
48
-
49
+
49
50
int maxSumSubmatrix (vector<vector<int >>& matrix, int k) {
50
-
51
+
51
52
int n = matrix.size ();
52
-
53
+
53
54
int m = matrix[0 ].size ();
54
-
55
+
55
56
int maxi = INT_MIN;
56
-
57
+
57
58
// fix the position two two rows and take cumulative sum of columns between two fixed rows
58
-
59
+
59
60
for (int start_row = 0 ; start_row < n; start_row++)
60
61
{
61
62
vector<int > col_array (m, 0 );
62
-
63
+
63
64
for (int end_row = start_row; end_row < n; end_row++)
64
65
{
65
66
// take cumulative sum of columns between two fixed rows
66
-
67
+
67
68
for (int col = 0 ; col < m; col++)
68
69
{
69
70
col_array[col] += matrix[end_row][col];
70
71
}
71
-
72
+
72
73
// find maximum subarray having sum less than equal to k
73
-
74
+
74
75
int curr_max = find_max (col_array, k);
75
-
76
+
76
77
// update the maximum sum
77
-
78
+
78
79
maxi = max (maxi, curr_max);
79
80
}
80
81
}
81
-
82
+
82
83
return maxi;
83
84
}
84
- };
85
+ };
0 commit comments