最大子矩阵和
来源:互联网 发布:水杉软件下载 编辑:程序博客网 时间:2024/05/18 18:14
题目描述:
一个M*N的矩阵,找到此矩阵的一个子矩阵,并且这个子矩阵的元素的和是最大的,输出这个最大的值。
例如:3*3的矩阵:
-1 3 -1
2 -1 3
-3 1 2
和最大的子矩阵是:
3 -1
-1 3
1 2
输入
第1行:M和N,中间用空格隔开(2 <= M,N <= 500)。N * M的矩阵
第2 - N + 1行:矩阵中的元素,每行M个数,中间用空格隔开。(-10^9 <= M[i] <= 10^9)
输出
输出和的最大值。如果所有数都是负数,就输出0。
输入示例
3 3
-1 3 -1
2 -1 3
-3 1 2
输出示例
7
import java.util.Scanner;public class MaxMatrix { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int M = scanner.nextInt(); int N = scanner.nextInt(); int[][] a = new int[N + 5][M + 5]; for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) { a[i][j] = scanner.nextInt(); } } int[][] total = a; for (int i = 2; i <= N; i++) { for (int j = 1; j <= M; j++) { total[i][j] += total[i-1][j]; } } int max = Integer.MIN_VALUE; //第i行 for (int i = 1; i <= N; i++) { //第j行 for (int j = i; j <= N; j++) { int[] result = new int[M + 5]; //把i行和j行之间的数压缩成一个以为数组,处理列 //k代表每一列 for (int k = 1; k <= M; k++) { if (i == 0) result[k] = total[j][k]; else { result[k] = total[j][k] - total[i - 1][k]; } } int tmp = maxSubsequence(result, M); if (tmp > max) max = tmp; } } System.out.println(max); } public static int maxSubsequence(int[] a, int N) { int max = Integer.MIN_VALUE; int sum = 0; for (int i = 1; i <= N; i++) { sum += a[i]; if (sum > max) max = sum; if (sum < 0) sum = 0; } return max; }}
阅读全文
0 0
- 最大子矩阵和
- 最大子矩阵和
- 最大子矩阵和
- 最大子矩阵和
- 最大子矩阵和
- 最大子矩阵和
- 最大子矩阵和
- 最大子矩阵和
- 最大子矩阵和
- 最大矩阵子和
- 最大子矩阵和
- 最大子矩阵和
- 最大和子矩阵
- 最大和子矩阵
- 最大子矩阵和
- 最大和子矩阵
- 最大子矩阵和
- 最大子矩阵和
- 必知必会的RocketMQ消息类型
- final
- px4中的mavlink协议
- Jekyll配合Github搭建个人博客
- WindowManager和WindowManager.LayoutParams的使用以及实现悬浮窗口的方法
- 最大子矩阵和
- swoole给特定用户推消息--基础思路
- Nginx与Apache优缺点比较
- GPS精确授时方法研究-基于ublox GPS
- Android Studio Gradle自动打包文档
- 漫步最优化二十四——二分搜索
- 排序算法的java实现-冒泡排序
- 查看Android SQLite数据库adb,error: more than one device and emulator
- python 文件压缩