| | 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.ArrangingCoins; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class ArrangingCoinsBinarySearch : IArrangingCoins |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(log n) |
| | 19 | | /// Space complexity - O(1) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="n"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public int ArrangeCoins(int n) |
| 10 | 24 | | { |
| 10 | 25 | | long left = 0; |
| 10 | 26 | | long right = n; |
| | 27 | |
|
| 33 | 28 | | while (left <= right) |
| 27 | 29 | | { |
| 27 | 30 | | var mid = left + ((right - left) / 2); |
| 27 | 31 | | var curr = mid * (mid + 1) / 2; |
| | 32 | |
|
| 27 | 33 | | if (curr == n) |
| 4 | 34 | | { |
| 4 | 35 | | return (int)mid; |
| | 36 | | } |
| | 37 | |
|
| 23 | 38 | | if (curr < n) |
| 14 | 39 | | { |
| 14 | 40 | | left = mid + 1; |
| 14 | 41 | | } |
| | 42 | | else |
| 9 | 43 | | { |
| 9 | 44 | | right = mid - 1; |
| 9 | 45 | | } |
| 23 | 46 | | } |
| | 47 | |
|
| 6 | 48 | | return (int)right; |
| 10 | 49 | | } |
| | 50 | | } |