Repository navigation
Expand file tree
/
Copy pathRECTANGLESUM.java
More file actions
122 lines (83 loc) · 2.15 KB
/
Copy pathRECTANGLESUM.java
File metadata and controls
122 lines (83 loc) · 2.15 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
/*
RECTANGLE SUM
Problem Description
Given a matrix of integers A of size N x M.
Calculate the sum of all submatrices and return the maximum among all those sums.
NOTE: Empty submatrix also need to be considered.
Problem Constraints
1 <= N, M <= 100
-10000 <= A[i] <= 10000
Input Format
The first and only argument given is the integer matrix A.
Output Format
Return the maximum sum among all those sums of all possible submatrices.
Example Input
Input 1:
A = [
[1, 3, -2]
[1, 4, 6]
[-4, -2, 1]
]
Input 2:
A = [
[-1, -1]
[-1, -1]
]
Example Output
Output 1:
13
Output 2:
0
Example Explanation
Explanation 1:
Submatrix giving maximum sum is :
[
[1, 3, -2]
[1, 4, 6]
]
Explanation 2:
Sum of empty submatrix will be 0.
*/
package DP;
public class RECTANGLESUM {
public static void main(String[] args) {
int[][] A = {{1, 3, -2},
{1, 4, 6},
{-4, -2, 1}};
System.out.println(solve(A));
int[][] B = {{-1, -1},
{-1, -1}};
System.out.println(solve(B));
}
public static int solve(int[][] A) {
int m = A.length;
int n = A[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] + A[i][j];
}
}
int maxSum = -1;
int minSum = Integer.MIN_VALUE;
for(int rowStart = 0; rowStart < m; rowStart++) {
for(int row = rowStart; row < m; row++){
int sum = 0;
for(int col = 0; col < n; col++) {
sum += preSum[row+1][col] - preSum[rowStart][col];
if(sum < 0) {
if(minSum < sum) {
minSum = sum;
}
sum = 0;
}
else if(maxSum < sum) {
maxSum = sum;
}
}
}
}
int res = maxSum == -1 ? minSum : maxSum;
return Math.max(res, 0);
}
}