| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 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.DividePlayersIntoTeamsOfEqualSkill; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class DividePlayersIntoTeamsOfEqualSkillDictionary : IDividePlayersIntoTeamsOfEqualSkill |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Time complexity - O(n) |
| | | 19 | | /// Space complexity - O(n) |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="skill"></param> |
| | | 22 | | /// <returns></returns> |
| | | 23 | | public long DividePlayers(int[] skill) |
| | 3 | 24 | | { |
| | 15 | 25 | | var totalSkill = skill.Aggregate<int, long>(0, (current, skillItem) => current + skillItem); |
| | | 26 | | |
| | 3 | 27 | | if (totalSkill % (skill.Length / 2) != 0) |
| | 1 | 28 | | { |
| | 1 | 29 | | return -1; |
| | | 30 | | } |
| | | 31 | | |
| | 2 | 32 | | var targetSkill = totalSkill / (skill.Length / 2); |
| | | 33 | | |
| | 2 | 34 | | var skillCountDictionary = new Dictionary<int, int>(); |
| | | 35 | | |
| | 2 | 36 | | long totalChemistry = 0; |
| | | 37 | | |
| | 22 | 38 | | foreach (var skillItem in skill) |
| | 8 | 39 | | { |
| | 8 | 40 | | var complement = (int)(targetSkill - skillItem); |
| | | 41 | | |
| | 8 | 42 | | if (skillCountDictionary.TryGetValue(complement, out var value) && value > 0) |
| | 4 | 43 | | { |
| | 4 | 44 | | totalChemistry += (long)skillItem * complement; |
| | | 45 | | |
| | 4 | 46 | | skillCountDictionary[complement]--; |
| | 4 | 47 | | } |
| | | 48 | | else |
| | 4 | 49 | | { |
| | 4 | 50 | | skillCountDictionary.TryAdd(skillItem, 0); |
| | | 51 | | |
| | 4 | 52 | | skillCountDictionary[skillItem]++; |
| | 4 | 53 | | } |
| | 8 | 54 | | } |
| | | 55 | | |
| | 6 | 56 | | if (skillCountDictionary.Values.Any(count => count > 0)) |
| | 0 | 57 | | { |
| | 0 | 58 | | return -1; |
| | | 59 | | } |
| | | 60 | | |
| | 2 | 61 | | return totalChemistry; |
| | 3 | 62 | | } |
| | | 63 | | } |