Java Array multidimensional Arrays get the largest sum

Introduction

Use variables maxRow and indexOfMaxRow to track the largest sum and index of the row.

For each row, compute its sum and update maxRow and indexOfMaxRow if the new sum is greater.


import java.util.Arrays;

public class Main {

  public static void main(String[] args) {
    int[][] matrix = { { 1, 2 }, { 3, 4 }, { 5, 6 } };

    System.out.println(Arrays.deepToString(matrix));
    int maxRow = 0;
    int indexOfMaxRow = 0;

    //your code here

    System.out.println("Row " + indexOfMaxRow + " has the maximum sum of " + maxRow);
  }// w w w.  j  a  v a2  s.  co m

}



import java.util.Arrays;

public class Main {

  public static void main(String[] args) {
    int[][] matrix = { { 1, 2 }, { 3, 4 }, { 5, 6 } };

    System.out.println(Arrays.deepToString(matrix));
    int maxRow = 0;
    int indexOfMaxRow = 0;

    // Get sum of the first row in maxRow
    for (int column = 0; column < matrix[0].length; column++) {
      maxRow += matrix[0][column];
    }

    for (int row = 1; row < matrix.length; row++) {
      int totalOfThisRow = 0;
      for (int column = 0; column < matrix[row].length; column++)
        totalOfThisRow += matrix[row][column];

      if (totalOfThisRow > maxRow) {
        maxRow = totalOfThisRow;
        indexOfMaxRow = row;
      }
    }

    System.out.println("Row " + indexOfMaxRow + " has the maximum sum of " + maxRow);
  }

}



PreviousNext

Related