MCPcopy Create free account
hub / github.com/algorithmzuo/videocode / Code06_MaxSubMatrixSum

Class Code06_MaxSubMatrixSum

src/videocode/Code06_MaxSubMatrixSum.java:3–160  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1package videocode;
2
3public class Code06_MaxSubMatrixSum {
4
5 // 非常好想
6 // 面试这么写一定没分的方法
7 public static int maxSubMatrixSum1(int[][] m) {
8 if (m == null || m.length == 0 || m[0] == null || m[0].length == 0) {
9 return 0;
10 }
11 int M = m.length;
12 int N = m[0].length;
13 int ans = Integer.MIN_VALUE;
14 for (int lur = 0; lur < M; lur++) {
15 for (int luc = 0; luc < N; luc++) {
16 // (lur, luc)
17 for (int rdr = lur; rdr < M; rdr++) {
18 for (int rdc = luc; rdc < N; rdc++) {
19 // (rdr, rdc)
20 int sum = 0;
21 for (int i = lur; i <= rdr; i++) {
22 for (int j = luc; j <= rdc; j++) {
23 sum += m[i][j];
24 }
25 }
26 ans = Math.max(ans, sum);
27 }
28 }
29 }
30 }
31 return ans;
32 }
33
34 public static int maxSubMatrixSum2(int[][] m) {
35 if (m == null || m.length == 0 || m[0] == null || m[0].length == 0) {
36 return 0;
37 }
38 int M = m.length;
39 int N = m[0].length;
40 int ans = Integer.MIN_VALUE;
41 for (int start = 0; start < M; start++) {
42 int[] arr = new int[N]; // 0 ,0,0,0,..
43 for (int cur = start; cur < M; cur++) {
44 for (int i = 0; i < N; i++) {
45 arr[i] += m[cur][i];
46 }
47 ans = Math.max(ans, maxSubArraySum(arr));
48 }
49 }
50 return ans;
51 }
52
53 public static int maxSubMatrixSum3(int[][] m) {
54 if (m == null || m.length == 0 || m[0] == null || m[0].length == 0) {
55 return 0;
56 }
57 m = m.length < m[0].length ? m : rotate(m);
58 int M = m.length;
59 int N = m[0].length;
60 int ans = Integer.MIN_VALUE;

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected