| | 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.FindSubsequenceOfLengthKWithTheLargestSum; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class FindSubsequenceOfLengthKWithTheLargestSumSorting : IFindSubsequenceOfLengthKWithTheLargestSum |
| | 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[] MaxSubsequence(int[] nums, int k) |
| 3 | 25 | | { |
| 3 | 26 | | var indexedNums = new (int Index, int Value)[nums.Length]; |
| | 27 | |
|
| 30 | 28 | | for (var i = 0; i < nums.Length; i++) |
| 12 | 29 | | { |
| 12 | 30 | | indexedNums[i] = (i, nums[i]); |
| 12 | 31 | | } |
| | 32 | |
|
| 18 | 33 | | Array.Sort(indexedNums, (a, b) => b.Value.CompareTo(a.Value)); |
| | 34 | |
|
| 3 | 35 | | var kIndexedNums = new (int Index, int Value)[k]; |
| | 36 | |
|
| 20 | 37 | | for (var i = 0; i < k; i++) |
| 7 | 38 | | { |
| 7 | 39 | | kIndexedNums[i] = indexedNums[i]; |
| 7 | 40 | | } |
| | 41 | |
|
| 8 | 42 | | Array.Sort(kIndexedNums, (a, b) => a.Index.CompareTo(b.Index)); |
| | 43 | |
|
| 3 | 44 | | var result = new int[k]; |
| | 45 | |
|
| 20 | 46 | | for (var i = 0; i < k; i++) |
| 7 | 47 | | { |
| 7 | 48 | | result[i] = kIndexedNums[i].Value; |
| 7 | 49 | | } |
| | 50 | |
|
| 3 | 51 | | return result; |
| 3 | 52 | | } |
| | 53 | | } |