Easy Solution || Well-Explained with Example || Intuitive || Mathematical-Approach || Beats 100%
Intuition\nWe don\'t need to actually subtract the values one-by-one.\nThink of it as a mathematical question and try to find a formula which fits this problem.
# Intuition\nWe don\'t need to actually subtract the values one-by-one.\nThink of it as a mathematical question and try to find a formula which fits this problem. A dry run will help you the best.\nLet\'s assume that k is somewhere in the middle of array.\ne.g - tickets[ ] = [2,3,6,4,3,6] and k=3\nNow, tickets[k] = 4\nWe will break this in two cases:\n\nCase-I:```i<=k```\nIf the current value, ```tickets[i]```, is less than target value, we will end the whole value by subtracting before ```tickets[k]``` reaches zero.\nFor i=0, ans += tickets[i];\nFor i=1, ans += tickets[i];\nIf it is greater, we will at least take tickets[k] \nFor i=2, ans += tickets[k];\nFor i=3, ans += tickets[k];\n\nCase-II: ```i>k```\nAgain, if current value is less, we will reduce it to 0 before ```tickets[k]``` reaches 0\nso ans += tickets[i]\nNow, here is the CATCH:\nIf current value is greater, we will take 1 second less than usual,\nBecause before we reach current value in the kth iteration, our ```tickets[k]``` would have already become zero. So, we will only take ```tickets[i]``` till (k-1)th iteration\nTherefore, ans += tickets[k]-1;\n\n# Approach\nApproach is as simple as it should be\n1. Initialise your answer variable, ```int ans=0```\n2. Now run a for-loop till tickets.size() \n3. ```if(i<=k) ans += min(tickets[i], tickets[k])```\n4. ```if(i>k) ans += min(tickets[i], ticekts[k]-1)```\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Code\n```C++ []\nclass Solution {\npublic:\n    int timeRequiredToBuy(vector<int>& tickets, int k) {\n        int ans=0;\n        for(int i=0;i<tickets.size();i++){\n            if(i<=k) ans += min(tickets[i] , tickets[k]);\n            if(i>k) ans += min(tickets[i] , tickets[k]-1);\n        }\n        return ans;\n    }\n};\n```\n```Python []\nclass Solution:\n    def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:\n        ans = 0\n        for i in range(len(tickets)):\n            if i <= k:\n                ans += min(tickets[i], tickets[k])\n            if i > k:\n                ans += min(tickets[i], tickets[k] - 1)\n        return ans\n```\n```Java []\nclass Solution {\n    public int timeRequiredToBuy(int[] tickets, int k) {\n        int ans = 0;\n        for (int i = 0; i < tickets.length; i++) {\n            if (i <= k) {\n                ans += Math.min(tickets[i], tickets[k]);\n            }\n            if (i > k) {\n                ans += Math.min(tickets[i], tickets[k]-1);\n            }\n        }\n        return ans;\n    }\n}\n```\n\nThis is my first Solution post. Hope it helped you.\nJust in case if it did, kindly upvote. \uD83D\uDE0A\nHave a nice day mate!
['Math', 'Python', 'C++', 'Java']