简体   繁体   中英

Largest subarray of specified dimensions in a 2d array JAVA

I'm trying to find the index of the upper-left corner of the subarray with the largest sum. I've seen algorithms that find the largest subarray, but those don't suit my needs because I need to set the dimensions of the subarray prior to using the algorithm.

/**
 * 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;
}

Here's what I have, but I can't seem to get it to work. Any suggestions for what I could do?

The javadoc of the findHorzPosition method says:

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

That means the band is h tall, ie the method should search for a rectangle with top row in row row0 .
As such, the code should not have a p 1 loop .

The javadoc also say:

@return The index of the leftmost column of the rectangle

The code is returning maxRow . The code should return the value of q 1 for the rectangle with the largest sum, not the value of i for the row with the largest sum.


1) The variable names are meaningless, making the code difficult to follow. Local variables with one-character names should only be used when the meaning is obvious, eg i , j , ... for indexes, or x , y , z for coordinates. In your code, p , q , i , and j are not obvious names. Rename q to left , i to row , and j to col .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM