Java dynamic programming algorithm: the largest sub-array

The largest sub-matrix of previous test questions
Problem description
Given an n*m matrix A, find a non-empty sub-matrix in A to maximize the sum of the elements in this sub-matrix.
Among them, the sub-matrix of A refers to a block in A whose rows and columns are continuous.

Input format
The first line of input contains two integers n, m, which represent the number of rows and columns of matrix A, respectively.
The next n rows, each row of m integers, represent matrix A.

Output format
Output a row, containing an integer, representing the sum of the elements in the largest sub-matrix in A.

Sample input:
3 3
-1 -4 3
3 4 -1
-5 -2 8

Sample output: 10

Sample description
Take the last column, and the sum is 10.

Data scale and conventions
For 50% data, 1<=n, m<=50;
for 100% data, 1<=n, m<=500, the absolute value of each element in A does not exceed 5000.

Idea: Find the prefix sum of each column, used to find the vertical sequence sum from layer i to layer j, and then find the largest horizontal sub-sequence sum to form the largest sub-array sum

import java.util.Scanner;

public class Main4 {
    
    

	static int[][] map;
	static int[][] cmap;
	static int[] rmap;

	public static void main(String[] args) {
    
    
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int m = sc.nextInt();
		map = new int[n + 1][m + 1];
		cmap = new int[n + 1][m + 1];
		rmap = new int[m + 1];
		int ans = Integer.MIN_VALUE;

		for (int i = 1; i <= n; i++) {
    
    
			for (int j = 1; j <= m; j++) {
    
    
				map[i][j] = sc.nextInt();
				// 前缀和
				cmap[i][j] = cmap[i - 1][j] + map[i][j];
			}
		}

		for (int i = 0; i <= n; i++) {
    
    
			for (int j = i + 1; j <= n; j++) {
    
    
				for (int k = 1; k <= m; k++) {
    
    
					// i层到j层的纵向和
					rmap[k] = cmap[j][k] - cmap[i][k];
				}
				// 求横向最大子序列和
				for (int k = 1; k <= m; k++) {
    
    
					if (rmap[k - 1] > 0)
						rmap[k] += rmap[k - 1];
					if (rmap[k] > ans)
						ans = rmap[k];
				}
			}
		}
		System.out.println(ans);
	}
}

Guess you like

Origin blog.csdn.net/qq_43610675/article/details/109053500