Advertisement
Ligh7_of_H3av3n

04. Maximal Sum

May 17th, 2024
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.83 KB | None | 0 0
  1. package Uprajnenie;
  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.  
  10.         // Read matrix dimensions
  11.         int rows = scanner.nextInt();
  12.         int cols = scanner.nextInt();
  13.         scanner.nextLine(); // Consume newline
  14.  
  15.         // Read the matrix
  16.         int[][] matrix = new int[rows][cols];
  17.         for (int i = 0; i < rows; i++) {
  18.             String[] rowValues = scanner.nextLine().split(" ");
  19.             for (int j = 0; j < cols; j++) {
  20.                 matrix[i][j] = Integer.parseInt(rowValues[j]);
  21.             }
  22.         }
  23.  
  24.         // Find the square 3x3 with maximal sum
  25.         int maxSum = Integer.MIN_VALUE;
  26.         int startRow = 0;
  27.         int startCol = 0;
  28.  
  29.         for (int i = 0; i <= rows - 3; i++) {
  30.             for (int j = 0; j <= cols - 3; j++) {
  31.                 int currentSum = findSquareSum(matrix, i, j);
  32.                 if (currentSum > maxSum) {
  33.                     maxSum = currentSum;
  34.                     startRow = i;
  35.                     startCol = j;
  36.                 }
  37.             }
  38.         }
  39.  
  40.         // Print the square and its sum
  41.         System.out.println("Sum = " + maxSum);
  42.         for (int i = startRow; i < startRow + 3; i++) {
  43.             for (int j = startCol; j < startCol + 3; j++) {
  44.                 System.out.print(matrix[i][j] + " ");
  45.             }
  46.             System.out.println();
  47.         }
  48.     }
  49.  
  50.     // Method to find the sum of a square 3x3
  51.     private static int findSquareSum(int[][] matrix, int startRow, int startCol) {
  52.         int sum = 0;
  53.         for (int i = startRow; i < startRow + 3; i++) {
  54.             for (int j = startCol; j < startCol + 3; j++) {
  55.                 sum += matrix[i][j];
  56.             }
  57.         }
  58.         return sum;
  59.     }
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement