| | | 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.WaterBottles2; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class WaterBottles2Math : IWaterBottles2 |
| | | 16 | | { |
| | | 17 | | private const int QuadraticA = 1; |
| | | 18 | | private const int LinearMultiplier = 2; |
| | | 19 | | private const int LinearOffset = 3; |
| | | 20 | | private const int ConstantMultiplier = -2; |
| | | 21 | | private const double Two = 2.0; |
| | | 22 | | private const double Four = 4.0; |
| | | 23 | | |
| | | 24 | | /// <summary> |
| | | 25 | | /// Time complexity - O(1) |
| | | 26 | | /// Space complexity - O(1) |
| | | 27 | | /// </summary> |
| | | 28 | | /// <param name="numBottles"></param> |
| | | 29 | | /// <param name="numExchange"></param> |
| | | 30 | | /// <returns></returns> |
| | | 31 | | public int MaxBottlesDrunk(int numBottles, int numExchange) |
| | 2 | 32 | | { |
| | 2 | 33 | | var quadraticB = (LinearMultiplier * numExchange) - LinearOffset; |
| | 2 | 34 | | var quadraticC = ConstantMultiplier * numBottles; |
| | | 35 | | |
| | 2 | 36 | | var discriminant = ((double)quadraticB * quadraticB) - (Four * QuadraticA * quadraticC); |
| | | 37 | | |
| | 2 | 38 | | var root = (-quadraticB + Math.Sqrt(discriminant)) / (Two * QuadraticA); |
| | | 39 | | |
| | 2 | 40 | | var maxExchanges = (int)Math.Ceiling(root); |
| | | 41 | | |
| | 2 | 42 | | return numBottles + maxExchanges - 1; |
| | 2 | 43 | | } |
| | | 44 | | } |