| | 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.FindTheMaximumSumOfNodeValues; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class FindTheMaximumSumOfNodeValuesIterative : IFindTheMaximumSumOfNodeValues |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n) |
| | 19 | | /// Space complexity - O(1) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="nums"></param> |
| | 22 | | /// <param name="k"></param> |
| | 23 | | /// <param name="edges"></param> |
| | 24 | | /// <returns></returns> |
| | 25 | | public long MaximumValueSum(int[] nums, int k, int[][] edges) |
| 4 | 26 | | { |
| 4 | 27 | | long sum = 0; |
| | 28 | |
|
| 4 | 29 | | long min = int.MaxValue; |
| | 30 | |
|
| 4 | 31 | | var count = 0; |
| | 32 | |
|
| 44 | 33 | | foreach (var num in nums) |
| 16 | 34 | | { |
| 16 | 35 | | if ((num ^ k) > num) |
| 7 | 36 | | { |
| 7 | 37 | | sum += num ^ k; |
| | 38 | |
|
| 7 | 39 | | min = Math.Min(min, (num ^ k) - num); |
| | 40 | |
|
| 7 | 41 | | count++; |
| 7 | 42 | | } |
| | 43 | | else |
| 9 | 44 | | { |
| 9 | 45 | | sum += num; |
| | 46 | |
|
| 9 | 47 | | min = Math.Min(min, num - (num ^ k)); |
| 9 | 48 | | } |
| 16 | 49 | | } |
| | 50 | |
|
| 4 | 51 | | return count % 2 == 0 ? sum : sum - min; |
| 4 | 52 | | } |
| | 53 | | } |