Advertisement
Danny_Berova

04.MaximalSum

Jan 27th, 2018
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.31 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace _04.MaximalSum
  6. {
  7.     public class MaximalSum
  8.     {
  9.         public static void Main(string[] args)
  10.         {
  11.             var input = Console.ReadLine();
  12.             int[] dimensions = input
  13.                  .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
  14.                  .Select(int.Parse)
  15.                  .ToArray();
  16.  
  17.             int[,] matrix = new int[dimensions[0], dimensions[1]];
  18.  
  19.             for (int rows = 0; rows < dimensions[0]; rows++)
  20.             {
  21.                 var rowIncomes = Console.ReadLine()
  22.                     .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
  23.                     .Select(int.Parse)
  24.                     .ToArray();
  25.                 for (int cols = 0; cols < dimensions[1]; cols++)
  26.                 {
  27.                     matrix[rows, cols] = rowIncomes[cols];
  28.                 }
  29.             }
  30.  
  31.             int maxSum = int.MinValue;
  32.             int rowIndex = 0;
  33.             int colIndex = 0;
  34.  
  35.             for (int rows = 0; rows < matrix.GetLength(0) - 2; rows++)
  36.             {
  37.                 for (int cols = 0; cols < matrix.GetLength(1) - 2; cols++)
  38.                 {
  39.                     var currentSum = matrix[rows, cols] + matrix[rows, cols + 1] + matrix[rows, cols + 2]
  40.                                      + matrix[rows + 1, cols] + matrix[rows + 1, cols + 1] + matrix[rows + 1, cols + 2]
  41.                                      + matrix[rows + 2, cols] + matrix[rows + 2, cols + 1] + matrix[rows + 2, cols + 2];
  42.  
  43.  
  44.                     if (currentSum > maxSum)
  45.                     {
  46.                         maxSum = currentSum;
  47.                         rowIndex = rows;
  48.                         colIndex = cols;
  49.                     }
  50.                 }
  51.             }
  52.  
  53.             Console.WriteLine($"Sum = {maxSum}");
  54.             Console.WriteLine($"{matrix[rowIndex, colIndex]} {matrix[rowIndex, colIndex + 1]} {matrix[rowIndex, colIndex + 2]}");
  55.             Console.WriteLine($"{matrix[rowIndex + 1, colIndex]} {matrix[rowIndex + 1, colIndex + 1]} {matrix[rowIndex + 1, colIndex + 2]}");
  56.             Console.WriteLine($"{matrix[rowIndex + 2, colIndex]} {matrix[rowIndex + 2, colIndex + 1]} {matrix[rowIndex + 2, colIndex + 2]}");
  57.  
  58.         }
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement