| | | 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.MinimumPairRemovalToSortArray1; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class MinimumPairRemovalToSortArray1Simulation : IMinimumPairRemovalToSortArray1 |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Time complexity - O(n^2) |
| | | 19 | | /// Space complexity - O(n) |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="nums"></param> |
| | | 22 | | /// <returns></returns> |
| | | 23 | | public int MinimumPairRemoval(int[] nums) |
| | 3 | 24 | | { |
| | 3 | 25 | | var list = new List<int>(nums); |
| | 3 | 26 | | var operations = 0; |
| | | 27 | | |
| | 14 | 28 | | while (!IsSorted(list)) |
| | 11 | 29 | | { |
| | 11 | 30 | | var minIndex = GetMinSumIndex(list); |
| | | 31 | | |
| | 11 | 32 | | list[minIndex] += list[minIndex + 1]; |
| | | 33 | | |
| | 11 | 34 | | list.RemoveAt(minIndex + 1); |
| | | 35 | | |
| | 11 | 36 | | operations++; |
| | 11 | 37 | | } |
| | | 38 | | |
| | 3 | 39 | | return operations; |
| | 3 | 40 | | } |
| | | 41 | | |
| | | 42 | | private static bool IsSorted(List<int> list) |
| | 14 | 43 | | { |
| | 46 | 44 | | for (var i = 0; i < list.Count - 1; i++) |
| | 20 | 45 | | { |
| | 20 | 46 | | if (list[i] > list[i + 1]) |
| | 11 | 47 | | { |
| | 11 | 48 | | return false; |
| | | 49 | | } |
| | 9 | 50 | | } |
| | | 51 | | |
| | 3 | 52 | | return true; |
| | 14 | 53 | | } |
| | | 54 | | |
| | | 55 | | private static int GetMinSumIndex(List<int> list) |
| | 11 | 56 | | { |
| | 11 | 57 | | var minSum = int.MaxValue; |
| | 11 | 58 | | var minSumIndex = 0; |
| | | 59 | | |
| | 140 | 60 | | for (var i = 0; i < list.Count - 1; i++) |
| | 59 | 61 | | { |
| | 59 | 62 | | var sum = list[i] + list[i + 1]; |
| | | 63 | | |
| | 59 | 64 | | if (sum >= minSum) |
| | 32 | 65 | | { |
| | 32 | 66 | | continue; |
| | | 67 | | } |
| | | 68 | | |
| | 27 | 69 | | minSum = sum; |
| | 27 | 70 | | minSumIndex = i; |
| | 27 | 71 | | } |
| | | 72 | | |
| | 11 | 73 | | return minSumIndex; |
| | 11 | 74 | | } |
| | | 75 | | } |