| | | 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.MaximumNumberOfDistinctElementsAfterOperations; |
| | | 13 | | |
| | | 14 | | public sealed class MaximumNumberOfDistinctElementsAfterOperationsSortingGreedy : |
| | | 15 | | IMaximumNumberOfDistinctElementsAfterOperations |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Time complexity - O(n log n) |
| | | 19 | | /// Space complexity - O(log n) |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="nums"></param> |
| | | 22 | | /// <param name="k"></param> |
| | | 23 | | /// <returns></returns> |
| | | 24 | | public int MaxDistinctElements(int[] nums, int k) |
| | 2 | 25 | | { |
| | 2 | 26 | | var numsLength = nums.Length; |
| | | 27 | | |
| | 2 | 28 | | if (k >= numsLength) |
| | 0 | 29 | | { |
| | 0 | 30 | | return numsLength; |
| | | 31 | | } |
| | | 32 | | |
| | 2 | 33 | | Array.Sort(nums); |
| | | 34 | | |
| | 2 | 35 | | if (nums[0] == nums[^1]) |
| | 1 | 36 | | { |
| | 1 | 37 | | return Math.Min(numsLength, (2 * k) + 1); |
| | | 38 | | } |
| | | 39 | | |
| | 1 | 40 | | var previous = nums[0] - k; |
| | | 41 | | |
| | 1 | 42 | | var distinctCount = 1; |
| | | 43 | | |
| | 12 | 44 | | for (var i = 1; i < numsLength; i++) |
| | 5 | 45 | | { |
| | 5 | 46 | | var num = nums[i]; |
| | | 47 | | |
| | 5 | 48 | | var current = Math.Min(Math.Max(previous + 1, num - k), num + k); |
| | | 49 | | |
| | 5 | 50 | | if (current <= previous) |
| | 0 | 51 | | { |
| | 0 | 52 | | continue; |
| | | 53 | | } |
| | | 54 | | |
| | 5 | 55 | | distinctCount++; |
| | | 56 | | |
| | 5 | 57 | | previous = current; |
| | 5 | 58 | | } |
| | | 59 | | |
| | 1 | 60 | | return distinctCount; |
| | 2 | 61 | | } |
| | | 62 | | } |