Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Lekciq;
- import java.util.Scanner;
- public class MaximumSumOfTwoByTwoSubmatrix {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- // Read matrix dimensions
- String[] dimensions = scanner.nextLine().split(", ");
- int rows = Integer.parseInt(dimensions[0]);
- int columns = Integer.parseInt(dimensions[1]);
- // Initialize the matrix
- int[][] matrix = new int[rows][columns];
- // Read matrix elements
- for (int i = 0; i < rows; i++) {
- String[] rowElements = scanner.nextLine().split(", ");
- for (int j = 0; j < columns; j++) {
- matrix[i][j] = Integer.parseInt(rowElements[j]);
- }
- }
- // Find the biggest sum of a 2x2 submatrix
- int maxSum = Integer.MIN_VALUE;
- int[][] maxSubmatrix = new int[2][2];
- for (int i = 0; i < rows - 1; i++) {
- for (int j = 0; j < columns - 1; j++) {
- int currentSum = matrix[i][j] + matrix[i][j + 1] +
- matrix[i + 1][j] + matrix[i + 1][j + 1];
- if (currentSum > maxSum) {
- maxSum = currentSum;
- maxSubmatrix[0][0] = matrix[i][j];
- maxSubmatrix[0][1] = matrix[i][j + 1];
- maxSubmatrix[1][0] = matrix[i + 1][j];
- maxSubmatrix[1][1] = matrix[i + 1][j + 1];
- }
- }
- }
- // Print the submatrix and its sum
- printMatrix(maxSubmatrix);
- System.out.println(maxSum);
- }
- // Method to print a matrix
- private static void printMatrix(int[][] matrix) {
- for (int[] ints : matrix) {
- for (int j = 0; j < matrix[0].length; j++) {
- System.out.print(ints[j]);
- if (j < matrix[0].length - 1) {
- System.out.print(" ");
- }
- }
- System.out.println();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement