首页 > 解决方案 > 二维数组JAVA中指定维度的最大子数组

问题描述

我试图找到总和最大的子数组左上角的索引。我见过找到最大子数组的算法,但这些算法不适合我的需要,因为我需要在使用算法之前设置子数组的维度。

/**
 * Finds the rectangle of height h and width w within the band
 * row0 <= row < row0 + h with the most "ink" in it, or the largest sum in it
 * @param int[][] image - A 2d array of light intensity values of each pixel in an image
 * @param h, w - Dimensions of the specified rectangle with height h and width w
 * @param row0 - the index of where it should start constructing rectangles? (I'm not sure)
 * @return The index of the leftmost column of the rectangle
 */
private int findHorzPosition(int[][] image, int row0, int h, int w) {
int maxSum = 0;
int maxRow = 0;
    for(int p = row0; p <= image.length - 1; p++) {
        int[][] tempArr = new int[image.length - row0][image[p].length - 1];
        for(int q = 0; q <= image[p].length - 1; q++) {
            tempArr[p][q] = image[p][q];

            for(int i = 0; i <= tempArr.length - 1; i++) {
                int rowSum = 0;
                for(int j = 0; j <= tempArr[i].length - 1; j++) {
                    rowSum += image[i][j];
                }

                if (rowSum > maxSum) {
                    maxSum = rowSum;
                    maxRow = i;
                }
            }
        }
    }
    return maxRow;
}

这就是我所拥有的,但我似乎无法让它工作。关于我能做什么的任何建议?

标签: javamatrixmultidimensional-array

解决方案


findHorzPosition方法的javadoc说:

查找带内“墨水”最多或总和最大的带的高度h和宽度矩形wrow0 <= row < row0 + h

这意味着乐队h很高,即该方法应该搜索一个在 row 中具有顶行的矩形row0
因此,代码不应p1 循环

javadoc还说:

@return矩形最左列的索引

代码正在返回maxRow。代码应该为总和最大的矩形返回值q1,而不是总和最大的的值。i


1) 变量名无意义,使代码难以理解。仅当含义很明显时才应使用具有单字符名称的局部变量,例如ij用于索引的 , , ... 或x用于y坐标z的 , 。在您的代码中,pqij不是显而易见的名称。重命名qleft、和。i_rowjcol


推荐阅读