| | | 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.DistributeCandies; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class DistributeCandiesLookupSpan : IDistributeCandies |
| | | 16 | | { |
| | | 17 | | private const int MinCandyType = -100_000; |
| | | 18 | | private const int MaxCandyType = 100_000; |
| | | 19 | | private const int Offset = -MinCandyType; |
| | | 20 | | private const int LookupSize = MaxCandyType - MinCandyType + 1; |
| | | 21 | | |
| | | 22 | | /// <summary> |
| | | 23 | | /// Time complexity - O(n) |
| | | 24 | | /// Space complexity - O(1) |
| | | 25 | | /// </summary> |
| | | 26 | | /// <param name="candyTypes"></param> |
| | | 27 | | /// <returns></returns> |
| | | 28 | | public int DistributeCandies(int[] candyTypes) |
| | 20 | 29 | | { |
| | 20 | 30 | | var maxCount = candyTypes.Length / 2; |
| | | 31 | | |
| | 20 | 32 | | Span<bool> candyTypesLookup = stackalloc bool[LookupSize]; |
| | | 33 | | |
| | 20 | 34 | | var uniqueCount = 0; |
| | | 35 | | |
| | 198 | 36 | | foreach (var candyType in candyTypes) |
| | 78 | 37 | | { |
| | 78 | 38 | | var index = GetIndex(candyType); |
| | | 39 | | |
| | 78 | 40 | | if (candyTypesLookup[index]) |
| | 29 | 41 | | { |
| | 29 | 42 | | continue; |
| | | 43 | | } |
| | | 44 | | |
| | 49 | 45 | | candyTypesLookup[index] = true; |
| | | 46 | | |
| | 49 | 47 | | uniqueCount++; |
| | | 48 | | |
| | 49 | 49 | | if (uniqueCount == maxCount) |
| | 18 | 50 | | { |
| | 18 | 51 | | return maxCount; |
| | | 52 | | } |
| | 31 | 53 | | } |
| | | 54 | | |
| | 2 | 55 | | return uniqueCount; |
| | 20 | 56 | | } |
| | | 57 | | |
| | | 58 | | private static int GetIndex(int candyType) |
| | 78 | 59 | | { |
| | 78 | 60 | | return candyType + Offset; |
| | 78 | 61 | | } |
| | | 62 | | } |