| | 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.LargestPerimeterTriangle; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class LargestPerimeterTriangleCountingSort : ILargestPerimeterTriangle |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n + k), where k is the maximum value in nums |
| | 19 | | /// Space complexity - O(n + k), where k is the maximum value in nums |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="nums"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public int LargestPerimeter(int[] nums) |
| 2 | 24 | | { |
| 2 | 25 | | var maxNum = nums.Max(); |
| | 26 | |
|
| 2 | 27 | | var count = new int[maxNum + 1]; |
| | 28 | |
|
| 20 | 29 | | foreach (var num in nums) |
| 7 | 30 | | { |
| 7 | 31 | | count[num]++; |
| 7 | 32 | | } |
| | 33 | |
|
| 2 | 34 | | var sortedNums = new int[nums.Length]; |
| | 35 | |
|
| 2 | 36 | | var index = 0; |
| | 37 | |
|
| 32 | 38 | | for (var i = maxNum; i >= 0; i--) |
| 14 | 39 | | { |
| 21 | 40 | | while (count[i]-- > 0) |
| 7 | 41 | | { |
| 7 | 42 | | sortedNums[index++] = i; |
| 7 | 43 | | } |
| 14 | 44 | | } |
| | 45 | |
|
| 8 | 46 | | for (var i = 0; i < sortedNums.Length - 2; i++) |
| 3 | 47 | | { |
| 3 | 48 | | if (sortedNums[i] < sortedNums[i + 1] + sortedNums[i + 2]) |
| 1 | 49 | | { |
| 1 | 50 | | return sortedNums[i] + sortedNums[i + 1] + sortedNums[i + 2]; |
| | 51 | | } |
| 2 | 52 | | } |
| | 53 | |
|
| 1 | 54 | | return 0; |
| 2 | 55 | | } |
| | 56 | | } |