| | | 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.SumOfElementsWithFrequencyDivisibleByK; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class SumOfElementsWithFrequencyDivisibleByKFrequencyArray : ISumOfElementsWithFrequencyDivisibleByK |
| | | 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 | | /// <returns></returns> |
| | | 24 | | public int SumDivisibleByK(int[] nums, int k) |
| | 3 | 25 | | { |
| | 3 | 26 | | Span<int> numsFrequency = stackalloc int[101]; |
| | | 27 | | |
| | 44 | 28 | | for (var i = 0; i < nums.Length; i++) |
| | 19 | 29 | | { |
| | 19 | 30 | | var num = nums[i]; |
| | | 31 | | |
| | 19 | 32 | | numsFrequency[num]++; |
| | 19 | 33 | | } |
| | | 34 | | |
| | 3 | 35 | | var sum = 0; |
| | | 36 | | |
| | 606 | 37 | | for (var i = 1; i < numsFrequency.Length; i++) |
| | 300 | 38 | | { |
| | 300 | 39 | | var numFrequency = numsFrequency[i]; |
| | | 40 | | |
| | 300 | 41 | | if (numFrequency == 0) |
| | 287 | 42 | | { |
| | 287 | 43 | | continue; |
| | | 44 | | } |
| | | 45 | | |
| | 13 | 46 | | if (numFrequency % k == 0) |
| | 3 | 47 | | { |
| | 3 | 48 | | sum += i * numFrequency; |
| | 3 | 49 | | } |
| | 13 | 50 | | } |
| | | 51 | | |
| | 3 | 52 | | return sum; |
| | 3 | 53 | | } |
| | | 54 | | } |