| | 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.LeftAndRightSumDifferences; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class LeftAndRightSumDifferencesPrefixSum : ILeftAndRightSumDifferences |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n) |
| | 19 | | /// Space complexity - O(n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="nums"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public int[] LeftRightDifference(int[] nums) |
| 2 | 24 | | { |
| 2 | 25 | | var leftSum = new int[nums.Length]; |
| | 26 | |
|
| 10 | 27 | | for (var i = 0; i < nums.Length - 1; i++) |
| 3 | 28 | | { |
| 3 | 29 | | leftSum[i + 1] = leftSum[i] + nums[i]; |
| 3 | 30 | | } |
| | 31 | |
|
| 2 | 32 | | var rightSum = new int[nums.Length]; |
| | 33 | |
|
| 10 | 34 | | for (var i = nums.Length - 1; i > 0; i--) |
| 3 | 35 | | { |
| 3 | 36 | | rightSum[i - 1] = rightSum[i] + nums[i]; |
| 3 | 37 | | } |
| | 38 | |
|
| 2 | 39 | | var result = new int[nums.Length]; |
| | 40 | |
|
| 14 | 41 | | for (var i = 0; i < nums.Length; i++) |
| 5 | 42 | | { |
| 5 | 43 | | result[i] = Math.Abs(leftSum[i] - rightSum[i]); |
| 5 | 44 | | } |
| | 45 | |
|
| 2 | 46 | | return result; |
| 2 | 47 | | } |
| | 48 | | } |