华为OD机试真题 - 最大矩阵和
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int[][] matrix = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j] = sc.nextInt();
}
}
getResult(matrix);
}
public static int getResult(int[][] map) {
int max = Integer.MIN_VALUE;
for (int i = 0; i < map.length; i++) {
max = Math.max(getSubMax(map[i]), max);
for (int j = 1; j < map.length; j++) {
max = Math.max(max, getSubMax(getMatixMax(map, i, j)));
}
}
return max;
}
public static int getSubMax(int[] sub) {
int res = sub[0];
int max = sub[0];
for (int i = 1; i < sub.length; i++) {
max = Math.max(sub[i] + max, sub[i]);
res = Math.max(res, max);
}
return res;
}
public static int[] getMatixMax(int[][] map, int begin, int end) {
int line = map[begin].length;
int[] zip = new int[line];
for (int i = 0; i < line; i++) {
for (int j = begin; j <= end; j++) {
zip[i] += map[j][i];
}
}
return zip;
}
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int[][] matrix = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j] = sc.nextInt();
}
}
getResult(matrix);
}
public static int getResult(int[][] map) {
int max = Integer.MIN_VALUE;
for (int i = 0; i < map.length; i++) {
max = Math.max(getSubMax(map[i]), max);
for (int j = 1; j < map.length; j++) {
max = Math.max(max, getSubMax(getMatixMax(map, i, j)));
}
}
return max;
}
public static int getSubMax(int[] sub) {
int res = sub[0];
int max = sub[0];
for (int i = 1; i < sub.length; i++) {
max = Math.max(sub[i] + max, sub[i]);
res = Math.max(res, max);
}
return res;
}
public static int[] getMatixMax(int[][] map, int begin, int end) {
int line = map[begin].length;
int[] zip = new int[line];
for (int i = 0; i < line; i++) {
for (int j = begin; j <= end; j++) {
zip[i] += map[j][i];
}
}
return zip;
}
全部评论
相关推荐
11-05 17:20
北京理工大学 Web前端 小火柴燃烧吧:如果是互联网的话,现在越来越卷了,你如果不主动去学习了解,领导可能就会感觉你态度有问题,我刚入职考个试成绩不好,领导直接就把我裁了。没办法,现在的风气就是这样,你不当牛马,多的是牛马
点赞 评论 收藏
分享