| | 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.TimeNeededToBuyTickets; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class TimeNeededToBuyTicketsIterative : ITimeNeededToBuyTickets |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n) |
| | 19 | | /// Space complexity - O(1) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="tickets"></param> |
| | 22 | | /// <param name="k"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public int TimeRequiredToBuy(int[] tickets, int k) |
| 7 | 25 | | { |
| 7 | 26 | | var time = 0; |
| | 27 | |
|
| 194 | 28 | | for (var i = 0; i < tickets.Length; i++) |
| 90 | 29 | | { |
| 90 | 30 | | if (i == k) |
| 7 | 31 | | { |
| 7 | 32 | | time += tickets[k]; |
| 7 | 33 | | } |
| | 34 | | else |
| 83 | 35 | | { |
| 83 | 36 | | if (tickets[i] >= tickets[k]) |
| 24 | 37 | | { |
| 24 | 38 | | if (i > k) |
| 14 | 39 | | { |
| 14 | 40 | | time += tickets[k] - 1; |
| 14 | 41 | | } |
| | 42 | | else |
| 10 | 43 | | { |
| 10 | 44 | | time += tickets[k]; |
| 10 | 45 | | } |
| 24 | 46 | | } |
| | 47 | | else |
| 59 | 48 | | { |
| 59 | 49 | | time += tickets[i]; |
| 59 | 50 | | } |
| 83 | 51 | | } |
| 90 | 52 | | } |
| | 53 | |
|
| 7 | 54 | | return time; |
| 7 | 55 | | } |
| | 56 | | } |