| | 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.MaximumMatrixSum; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class MaximumMatrixSumBruteForce : IMaximumMatrixSum |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n^2) |
| | 19 | | /// Space complexity - O(1) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="matrix"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public long MaxMatrixSum(int[][] matrix) |
| 2 | 24 | | { |
| 2 | 25 | | long sum = 0; |
| 2 | 26 | | var minAbsValue = int.MaxValue; |
| 2 | 27 | | var negativeCount = 0; |
| | 28 | |
|
| 16 | 29 | | foreach (var row in matrix) |
| 5 | 30 | | { |
| 41 | 31 | | foreach (var cell in row) |
| 13 | 32 | | { |
| 13 | 33 | | sum += Math.Abs(cell); |
| | 34 | |
|
| 13 | 35 | | if (cell < 0) |
| 5 | 36 | | { |
| 5 | 37 | | negativeCount++; |
| 5 | 38 | | } |
| | 39 | |
|
| 13 | 40 | | minAbsValue = Math.Min(minAbsValue, Math.Abs(cell)); |
| 13 | 41 | | } |
| 5 | 42 | | } |
| | 43 | |
|
| 2 | 44 | | if (negativeCount % 2 != 0) |
| 1 | 45 | | { |
| 1 | 46 | | sum -= 2 * minAbsValue; |
| 1 | 47 | | } |
| | 48 | |
|
| 2 | 49 | | return sum; |
| 2 | 50 | | } |
| | 51 | | } |