Advertisement
alidzhikov

MaximalSum

May 8th, 2015
956
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.11 KB | None | 0 0
  1. using System;
  2. class MaximalSum
  3. {
  4.     static void Main()
  5.     {
  6.         string[] rowsAndColsInput = Console.ReadLine().Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
  7.  
  8.         int rows = int.Parse(rowsAndColsInput[0]) + 1;
  9.         int cols = int.Parse(rowsAndColsInput[1]) + 1;
  10.         int[,] matrix = new int[rows, cols];
  11.         for (int row = 0; row < rows; row++)
  12.         {
  13.             string[] currentRowNumbersAsStrings =
  14.                         Console.ReadLine().Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
  15.             for (int col = 0; col < cols; col++)
  16.             {
  17.                 matrix[row, col] = int.Parse(currentRowNumbersAsStrings[col]);
  18.             }
  19.         }
  20.  
  21.         int bestSum = int.MinValue;
  22.         int currentSum = 0;
  23.         int[,] elementsWithMaxSum = new int[3, 3];
  24.         for (int row = 0; row < rows - 2; row++)
  25.         {
  26.             for (int col = 0; col < cols - 2; col++)
  27.             {
  28.                 currentSum = matrix[row, col] + matrix[row, col + 1] + matrix[row, col + 2] +
  29.                              matrix[row + 1, col] + matrix[row + 1, col + 1] + matrix[row + 1, col + 2] +
  30.                              matrix[row + 2, col] + matrix[row + 2, col + 1] + matrix[row + 2, col + 2];
  31.                 if (currentSum > bestSum)
  32.                 {
  33.                     bestSum = currentSum;
  34.                     for (int i = 0; i < elementsWithMaxSum.GetLength(0); i++)
  35.                     {
  36.                         for (int j = 0; j < elementsWithMaxSum.GetLength(1); j++)
  37.                         {
  38.                             elementsWithMaxSum[i, j] = matrix[row + i, col + j];
  39.                         }
  40.                     }
  41.                 }
  42.             }
  43.         }
  44.  
  45.         Console.WriteLine("Sum = {0}", bestSum);
  46.         for (int row = 0; row < elementsWithMaxSum.GetLength(0); row++)
  47.         {
  48.             for (int col = 0; col < elementsWithMaxSum.GetLength(1); col++)
  49.             {
  50.                 Console.Write("{0,2} ", elementsWithMaxSum[row, col]);
  51.             }
  52.             Console.WriteLine();
  53.         }
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement