in this tutorial, we will write a java program to find the sum of the Largest Forward Diagonal in an Arraylist (matrix).
Java Program to find the sum of the Largest Forward Diagonal
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | import java.util.ArrayList; public class Main { public static int diagonalSum(ArrayList<ArrayList<Integer>> matrix, int startRow, int startCol) { int sum = 0; int rows = matrix.size(); int cols = matrix.get(0).size(); while (startRow < rows && startCol < cols) { sum += matrix.get(startRow).get(startCol); startRow++; startCol++; } return sum; } public static int sumOfLargestForwardDiagonal(ArrayList<ArrayList<Integer>> matrix) { int rows = matrix.size(); int cols = matrix.get(0).size(); int maxSum = Integer.MIN_VALUE; // Iterate through each row to start a forward diagonal for (int row = 0; row < rows; row++) { maxSum = Math.max(maxSum, diagonalSum(matrix, row, 0)); } // Iterate through each column to start a forward diagonal for (int col = 1; col < cols; col++) { maxSum = Math.max(maxSum, diagonalSum(matrix, 0, col)); } return maxSum; } public static void main(String[] args) { ArrayList<ArrayList<Integer>> matrix = new ArrayList<>(); matrix.add(new ArrayList<Integer>() {{ add(1); add(2); add(3); }}); matrix.add(new ArrayList<Integer>() {{ add(9); add(5); add(6); }}); matrix.add(new ArrayList<Integer>() {{ add(7); add(9); add(9); }}); int sumOfLargestDiagonal = sumOfLargestForwardDiagonal(matrix); System.out.println("Sum of largest forward diagonal: " + sumOfLargestDiagonal); } } |
Output:
1 2 | Sum of largest forward diagonal: 18 |
Explanation:
It calculates the sum of each forward diagonal and returns the sum of the largest forward diagonal. The diagonalSum method calculates the sum of a forward diagonal, and the sumOfLargestForwardDiagonal method finds the largest sum among all forward diagonals. Finally, the main method calls sumOfLargestForwardDiagonal to find and print the sum of the largest forward diagonal in the given matrix.
The forward diagonals are:
- Starting from
(0,0)
: 1 - Starting from
(1,0)
: 9 + 2 = 11 - Starting from
(2,0)
: 7 + 5 + 3 = 15 - Starting from
(0,1)
: 2 + 5 + 9 = 16 - Starting from
(0,2)
: 3 + 6 + 9 = 18 - Starting from
(0,3)
(out of bounds) - Starting from
(1,1)
(out of bounds) - Starting from
(2,1)
(out of bounds)
Among these sums, the largest sum is 18.