-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMaximumSumRectangle.java
81 lines (73 loc) · 2.58 KB
/
MaximumSumRectangle.java
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// Java Program to find max sum rectangular submatrix
import java.io.*;
import java.lang.*;
import java.util.*;
class MaximumSumRectangle {
// Function to find maximum sum rectangular
// submatrix
private static int maxSumRectangle(int[][] mat)
{
int m = mat.length;
int n = mat[0].length;
int preSum[][] = new int[m + 1][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
preSum[i + 1][j] = preSum[i][j] + mat[i][j];
}
}
int maxSum = -1;
int minSum = Integer.MIN_VALUE;
int negRow = 0, negCol = 0;
int rStart = 0, rEnd = 0, cStart = 0, cEnd = 0;
for (int rowStart = 0; rowStart < m; rowStart++) {
for (int row = rowStart; row < m; row++) {
int sum = 0;
int curColStart = 0;
for (int col = 0; col < n; col++) {
sum += preSum[row + 1][col]
- preSum[rowStart][col];
if (sum < 0) {
if (minSum < sum) {
minSum = sum;
negRow = row;
negCol = col;
}
sum = 0;
curColStart = col + 1;
}
else if (maxSum < sum) {
maxSum = sum;
rStart = rowStart;
rEnd = row;
cStart = curColStart;
cEnd = col;
}
}
}
}
// Printing final values
if (maxSum == -1) {
System.out.println("from row - " + negRow
+ " to row - " + negRow);
System.out.println("from col - " + negCol
+ " to col - " + negCol);
}
else {
System.out.println("from row - " + rStart
+ " to row - " + rEnd);
System.out.println("from col - " + cStart
+ " to col - " + cEnd);
}
return maxSum == -1 ? minSum : maxSum;
}
// Driver Code
public static void main(String[] args)
{
int arr[][] = new int[][] { { 1, 2, -1, -4, -20 },
{ -8, -3, 4, 2, 1 },
{ 3, 8, 10, 1, 3 },
{ -4, -1, 1, 7, -6 } };
// Function call
System.out.println(maxSumRectangle(arr));
}
}