Didart

Maximal Sum

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