Advertisement
SvetoslavUzunov

Find max sum of dynamic Submatrix

Feb 17th, 2022
767
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.21 KB | None | 0 0
  1. using System;
  2. using System.Linq;
  3. using System.Collections.Generic;
  4.  
  5. public class Program
  6. {
  7.     public static void Main()
  8.     {
  9.         var input = Console.ReadLine().Split().Select(int.Parse).ToArray();
  10.  
  11.         var rows = input[0];
  12.         var cols = input[1];
  13.  
  14.         var matrix = new int[rows, cols];
  15.  
  16.         for (var row = 0; row < matrix.GetLength(0); row++)
  17.         {
  18.             var inputElement = Console.ReadLine().Split().Select(int.Parse).ToArray();
  19.             for (int col = 0; col < matrix.GetLength(1); col++)
  20.             {
  21.                 matrix[row, col] = inputElement[col];
  22.             }
  23.         }
  24.  
  25.         var subMatrixRow = int.Parse(Console.ReadLine());
  26.         var subMatrixCol = int.Parse(Console.ReadLine());
  27.  
  28.         var maxSum = int.MinValue;
  29.         var startRowIndex = 0;
  30.         var startColIndex = 0;
  31.         if (subMatrixRow <= matrix.GetLength(0) && subMatrixCol <= matrix.GetLength(1))
  32.         {
  33.             for (int row = 0; row < matrix.GetLength(0); row++)
  34.             {
  35.                 for (int col = 0; col < matrix.GetLength(1); col++)
  36.                 {
  37.                     var tempMaxSum = 0;
  38.                     if (row + subMatrixRow <= matrix.GetLength(0) && col + subMatrixCol <= matrix.GetLength(1))
  39.                     {
  40.                         for (int i = row; i < row + subMatrixRow; i++)
  41.                         {
  42.                             for (int j = col; j < col + subMatrixCol; j++)
  43.                             {
  44.                                 tempMaxSum += matrix[i, j];
  45.                             }
  46.                         }
  47.                     }
  48.  
  49.                     if (tempMaxSum > maxSum)
  50.                     {
  51.                         maxSum = tempMaxSum;
  52.                         startRowIndex = row;
  53.                         startColIndex = col;
  54.                     }
  55.                 }
  56.             }
  57.         }
  58.  
  59.         for (int row = 0; row < subMatrixRow; row++)
  60.         {
  61.             for (int col = 0; col < subMatrixCol; col++)
  62.             {
  63.                 Console.Write(matrix[startRowIndex + row, startColIndex + col] + " ");
  64.             }
  65.             Console.WriteLine();
  66.         }
  67.         Console.WriteLine(maxSum);
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement