-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path101.max_sum_rectangle.java
More file actions
63 lines (55 loc) · 1.78 KB
/
Copy path101.max_sum_rectangle.java
File metadata and controls
63 lines (55 loc) · 1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// Maximum sum Rectangle
// Given a 2D matrix M of dimensions RxC. Find the maximum sum submatrix in it.
// https://practice.geeksforgeeks.org/problems/maximum-sum-rectangle2948/1#
// { Driver Code Starts
// Initial Template for Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String args[]) throws IOException {
BufferedReader read =
new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(read.readLine());
while (t-- > 0) {
int N, M, x, y;
String S[] = read.readLine().split(" ");
N = Integer.parseInt(S[0]);
M = Integer.parseInt(S[1]);
int a[][] = new int[N][M];
for (int i = 0; i < N; i++) {
String s[] = read.readLine().split(" ");
for (int j = 0; j < M; j++) a[i][j] = Integer.parseInt(s[j]);
}
Solution ob = new Solution();
System.out.println(ob.maximumSumRectangle(N, M, a));
}
}
}// } Driver Code Ends
// User function Template for Java
class Solution {
int maximumSumRectangle(int r, int c, int m[][]) {
// code here
int max = Integer.MIN_VALUE;
int [] dp = new int[c];
for(int i=0;i<r;i++){
for(int j=i;j<r;j++){
for(int k=0;k<c;k++){
dp[k] += m[j][k];
}
max = Math.max(max, kadane(dp));
}
Arrays.fill(dp, 0);
}
return max;
}
public static int kadane(int [] dp){
int sum=dp[0], max=dp[0];
for(int i=1;i<dp.length;i++){
sum+= dp[i];
if(sum<dp[i])
sum = dp[i];
max = Math.max(sum, max);
}
return max;
}
}