| | 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.FindScoreOfAnArrayAfterMarkingAllElements; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class FindScoreOfAnArrayAfterMarkingAllElementsSorting : IFindScoreOfAnArrayAfterMarkingAllElements |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n log n) |
| | 19 | | /// Space complexity - O(n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="nums"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public long FindScore(int[] nums) |
| 2 | 24 | | { |
| 2 | 25 | | long score = 0; |
| 2 | 26 | | var markedElements = new bool[nums.Length]; |
| | 27 | |
|
| 14 | 28 | | var elements = nums.Select((value, index) => (Value: value, Index: index)) |
| 12 | 29 | | .OrderBy(e => e.Value) |
| 14 | 30 | | .ThenBy(e => e.Index); |
| | 31 | |
|
| 30 | 32 | | foreach (var (value, index) in elements) |
| 12 | 33 | | { |
| 12 | 34 | | if (markedElements[index]) |
| 6 | 35 | | { |
| 6 | 36 | | continue; |
| | 37 | | } |
| | 38 | |
|
| 6 | 39 | | score += value; |
| 6 | 40 | | markedElements[index] = true; |
| | 41 | |
|
| 6 | 42 | | if (index > 0) |
| 5 | 43 | | { |
| 5 | 44 | | markedElements[index - 1] = true; |
| 5 | 45 | | } |
| | 46 | |
|
| 6 | 47 | | if (index < nums.Length - 1) |
| 4 | 48 | | { |
| 4 | 49 | | markedElements[index + 1] = true; |
| 4 | 50 | | } |
| 6 | 51 | | } |
| | 52 | |
|
| 2 | 53 | | return score; |
| 2 | 54 | | } |
| | 55 | | } |