2d数组Java中的最大总和

时间:2016-07-31 14:08:10

标签: java arrays multidimensional-array

我有一个二维数组(一个矩阵),我需要找到可以通过从任何位置开始并向右或向下向下直到我结束时收集的最大总和。我必须给出一个迭代的解决方案。

enter image description here

这是我的代码

    static int maxValue(double[][] field, int posR, int posC) {
    int r = field.length;
    int c = field[0].length;
    int sum = 0;
    double[][] temp = new double[r][c];
    for (int i = posR; i < r; i++) {
        for (int j = posC; j < c; j++) {
            if (i == posR && j == posC) {
                temp[i][j] = field[posR][posC];
                posR++; posC++;
            } else if (i == field.length-1) {
                temp[i][j] = field[i][j];
                break;
            } else if (j == field.length-1) {
                temp[i][j] = field[i][j];
                break;
            } else {
                temp[i][j] = Math.max(field[i+1][j-1], field[i+1][j+1]);
            }
        }
    }
    for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++) {
            sum += temp[i][j];
        }

    }
    return sum;
}

}

2 个答案:

答案 0 :(得分:1)

这是一个迭代解决方案的想法:你可以向下滑动一行,在底部你可以找到最大值。听起来很疯狂?让我用代码解释一下:

public static double maxZicZacSum(double[][] matrix) {
  double[] row = matrix[0]; // assign first row
  int n = row.length;
  for (int i = 1; i < matrix.length; i++) { // for each row, except the first
    double[] nextRow = new double[n];
    // special cases (left and right edge)
    nextRow[0] = row[1] <= 0 ? matrix[i][0] : row[1] + matrix[i][0];
    nextRow[n - 1] = row[n - 2] <= 0 ? matrix[i][n - 1] : row[n - 2] + matrix[i][n - 1];
    for (int j = 1; j < n - 1; j++) { // for each column except the edges
      double d = Math.max(row[j - 1], row[j + 1]); // which cell above is better?
      // if d is > 0, then the sum is also better, otherwise use (i,j) as new start
      nextRow[j] = d <= 0 ? matrix[i][j] : d + matrix[i][j];
    }
    row = nextRow; // finally assign nextRow to row for the next iteration
  }
  // the highest value in row is now the max sum
  double max = row[0];
  for (int i = 1; i < n; i++)
    if (row[i] > max)
      max = row[i];
  return max;
}

答案 1 :(得分:0)

一般来说,这是一个动态编程问题。

逻辑是(第0行是左上角)

pollutantmean <- function(directory = "specdata", pollutant) {

   files_full <- Sys.glob(paste0(directory,"/*.csv"))[1:332]  # FIRST 332 CSVs IN DIRECTORY

   dfList <- lapply(files_full, read.csv, header=TRUE)
   df <- do.call(rbind, dfList)

   gooddata <- na.omit(df)
   pmean <- ifelse(pollutant == "sulfate", mean(gooddata[,2]), mean(gooddata[,3]))

}

现在,您会注意到这是一个递归定义,因此实际上不需要for循环。

所以,以轻微的伪代码

F(row, col) = valueAt(row, col) + max(F(row + 1, col - 1), F(row + 1, col + 1) 

从任何位置开始,您应该能够调用该方法,并且它将以递归方式对值进行求和并返回最大路径。