| | 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.MaximumBeautyOfAnArrayAfterApplyingOperation; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class MaximumBeautyOfAnArrayAfterApplyingOperationLineSweep : IMaximumBeautyOfAnArrayAfterApplyingOperation |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n log n) |
| | 19 | | /// Space complexity - O(n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="nums"></param> |
| | 22 | | /// <param name="k"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public int MaximumBeauty(int[] nums, int k) |
| 2 | 25 | | { |
| 2 | 26 | | if (nums.Length == 1) |
| 0 | 27 | | { |
| 0 | 28 | | return 1; |
| | 29 | | } |
| | 30 | |
|
| 2 | 31 | | var ranges = new (int Position, int Type)[nums.Length * 2]; |
| | 32 | |
|
| 20 | 33 | | for (var i = 0; i < nums.Length; i++) |
| 8 | 34 | | { |
| 8 | 35 | | ranges[i] = (nums[i] - k, 1); |
| 8 | 36 | | ranges[i + nums.Length] = (nums[i] + k, -1); |
| 8 | 37 | | } |
| | 38 | |
|
| 2 | 39 | | Array.Sort(ranges, |
| 24 | 40 | | (x, y) => x.Position == y.Position ? y.Type.CompareTo(x.Type) : x.Position.CompareTo(y.Position)); |
| | 41 | |
|
| 2 | 42 | | var maximumBeauty = 0; |
| 2 | 43 | | var count = 0; |
| | 44 | |
|
| 36 | 45 | | for (var i = 0; i < ranges.Length; i++) |
| 16 | 46 | | { |
| 16 | 47 | | count += ranges[i].Type; |
| | 48 | |
|
| 16 | 49 | | maximumBeauty = Math.Max(maximumBeauty, count); |
| 16 | 50 | | } |
| | 51 | |
|
| 2 | 52 | | return maximumBeauty; |
| 2 | 53 | | } |
| | 54 | | } |