✅ 🔥Time to buy | Java | O(n) - time O(1) - space | 100% ✅ 🔥
Hi, \n\nThe rationale behind this approach is that when standing in a queue for tickets, if each person can only purchase one ticket at a time, the person ahead
Hi, \n\nThe rationale behind this approach is that when standing in a queue for tickets, if each person can only purchase one ticket at a time, the person ahead of you can obtain a maximum of the same number of tickets you currently hold, while the person behind you can acquire a maximum of the tickets you need minus one.\n\n**Steps**\n* Know how many tickets you need and store it in a variable (**val**).\n* To keep track of time, initialize a variable (**res**) and assign it to 0.\n* Now, iterate through the array:\n\t* If the index of the person is less than or equal to yours, then they can get a maximum of either your number of tickets or the number of tickets they need.\n\t* If the index is greater than yours, then they can get a maximum of either your number of tickets minus one or the number of tickets they need.\n* Add these to the result (**res**) and return the result.\n\n**Time complexity - O(n)\nSpace complexity - O(1)**\n\nHere is the code for the same.. Happy coding..\n\n```\n    public int timeRequiredToBuy(int[] tickets, int k) {\n        int val = tickets[k], res=0;\n        for(int i=0; i<tickets.length; i++){\n            if(i<=k){\n                res = res+Math.min(tickets[i], val);\n            } else{\n                res = res+Math.min(tickets[i], val-1);\n            }\n        }\n        return res;\n    }\n\t\n\t```\n\tPlease take a second to upvote and motivate others..
['Math', 'Java']