Didart

Maximum Sum of 2x2 Submatrix

Jan 3rd, 2023
817
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.28 KB | None | 0 0
  1. package MultidimensionalArrays;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class MaximumSumOf2x2Submatrix {
  6.     public static void main(String[] args) {
  7.         Scanner scanner = new Scanner(System.in);
  8.  
  9.         String[] input = scanner.nextLine().split(", ");
  10.  
  11.         int rows = Integer.parseInt(input[0]);
  12.         int cols = Integer.parseInt(input[1]);
  13.  
  14.         String[][] matrix = new String[rows][cols];
  15.  
  16.         for (int i = 0; i < rows; i++) {
  17.             matrix[i] = scanner.nextLine().split(", ");
  18.         }
  19.  
  20.         int maxSum = Integer.MIN_VALUE;
  21.         int row = 0;
  22.         int col = 0;
  23.  
  24.         for (int r = 0; r < matrix.length - 1; r++) {
  25.             for (int c = 0; c < matrix[r].length - 1; c++) {
  26.                 int sum = Integer.parseInt(matrix[r][c]) + Integer.parseInt(matrix[r][c + 1]);
  27.                 sum += Integer.parseInt(matrix[r + 1][c]) + Integer.parseInt(matrix[r + 1][c + 1]);
  28.                 if (sum > maxSum) {
  29.                     maxSum = sum;
  30.                     row = r;
  31.                     col = c;
  32.                 }
  33.             }
  34.         }
  35.  
  36.         System.out.println(matrix[row][col] + " " + matrix[row][col + 1]);
  37.         System.out.println(matrix[row + 1][col] + " " + matrix[row + 1][col + 1]);
  38.         System.out.println(maxSum);
  39.     }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment