最大子矩阵和动态规划Java代码
时间: 2023-12-17 07:26:04 浏览: 72
关于动态规划求最大子段和的Java代码写法
5星 · 资源好评率100%
最大子矩阵问题是指在一个矩阵中,找到一个子矩阵,使得子矩阵中所有元素的和最大。而动态规划是解决最大子矩阵问题的一种常用方法。下面是Java代码实现:
```
public class MaxSubMatrix {
public int getMaxSubMatrix(int[][] matrix) {
int maxSum = Integer.MIN_VALUE;
int rowNum = matrix.length;
int colNum = matrix[0].length;
int[] temp = new int[colNum];
for (int i = 0; i < rowNum; i++) {
for (int j = i; j < rowNum; j++) {
for (int k = 0; k < colNum; k++) {
temp[k] += matrix[j][k];
}
int sum = maxSubArray(temp);
if (sum > maxSum) {
maxSum = sum;
}
}
Arrays.fill(temp, 0);
}
return maxSum;
}
private int maxSubArray(int[] nums) {
int maxSum = Integer.MIN_VALUE;
int curSum = 0;
for (int num : nums) {
curSum = Math.max(curSum + num, num);
maxSum = Math.max(maxSum, curSum);
}
return maxSum;
}
}
```
阅读全文