| | 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.BagOfTokens; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class BagOfTokensTwoPointers : IBagOfTokens |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n log n) |
| | 19 | | /// Space complexity - O(1) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="tokens"></param> |
| | 22 | | /// <param name="power"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public int BagOfTokensScore(int[] tokens, int power) |
| 3 | 25 | | { |
| 3 | 26 | | var score = 0; |
| | 27 | |
|
| 3 | 28 | | Array.Sort(tokens); |
| | 29 | |
|
| 3 | 30 | | var left = 0; |
| 3 | 31 | | var right = tokens.Length - 1; |
| | 32 | |
|
| 8 | 33 | | while (left <= right) |
| 7 | 34 | | { |
| 7 | 35 | | if (power >= tokens[left]) |
| 4 | 36 | | { |
| 4 | 37 | | power -= tokens[left]; |
| 4 | 38 | | score++; |
| 4 | 39 | | left++; |
| 4 | 40 | | } |
| 3 | 41 | | else if (score >= 1 && left < right) |
| 1 | 42 | | { |
| 1 | 43 | | power += tokens[right]; |
| 1 | 44 | | score--; |
| 1 | 45 | | right--; |
| 1 | 46 | | } |
| | 47 | | else |
| 2 | 48 | | { |
| 2 | 49 | | break; |
| | 50 | | } |
| 5 | 51 | | } |
| | 52 | |
|
| 3 | 53 | | return score; |
| 3 | 54 | | } |
| | 55 | | } |