| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.MatrixDiagonalSum; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class MatrixDiagonalSumIterative : IMatrixDiagonalSum |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n) |
| | 19 | | /// Space complexity - O(1) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="mat"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public int DiagonalSum(int[][] mat) |
| 3 | 24 | | { |
| 3 | 25 | | var result = 0; |
| | 26 | |
|
| 22 | 27 | | for (var i = 0; i < mat.Length; i++) |
| 8 | 28 | | { |
| 8 | 29 | | result += mat[i][i]; |
| 8 | 30 | | result += mat[i][mat.Length - i - 1]; |
| 8 | 31 | | } |
| | 32 | |
|
| 3 | 33 | | if (mat.Length % 2 != 0) |
| 2 | 34 | | { |
| 2 | 35 | | result -= mat[mat.Length / 2][mat.Length / 2]; |
| 2 | 36 | | } |
| | 37 | |
|
| 3 | 38 | | return result; |
| 3 | 39 | | } |
| | 40 | | } |