𝗗𝗮𝘆 𝟲𝟴/𝟭𝟬𝟬 — 𝗧𝗶𝗺𝗲 𝗡𝗲𝗲𝗱𝗲𝗱 𝘁𝗼 𝗕𝘂𝘆 𝗧𝗶𝗰𝗸𝗲𝘁𝘀 🎟️ Day 68. Sometimes you don't need to simulate. You just need to think. 𝗧𝗼𝗱𝗮𝘆'𝘀 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: ✅ #𝟮𝟬𝟳𝟯: Time Needed to Buy Tickets (Easy) 𝗧𝗵𝗲 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: People in a queue buying tickets. Each person needs a certain number of tickets. They buy one at a time and go to the back of the line if they need more. How long until person k finishes buying? 𝗧𝗵𝗲 𝗜𝗻𝘀𝗶𝗴𝗵𝘁: You could simulate the queue. Or you could realize: People before position k contribute min(tickets[i], target) People after position k contribute min(tickets[i], target - 1) Why target - 1 for people after? Because person k finishes before they get another turn. No simulation needed. Just math. 𝗠𝘆 𝗦𝗼𝗹𝘂𝘁𝗶𝗼𝗻: One loop. For each person: If before or at position k: add min(tickets[i], tickets[k]) If after position k: add min(tickets[i], tickets[k] - 1) Sum it up. Done. Time: O(n), Space: O(1) 𝗪𝗵𝘆 𝗜𝘁 𝗠𝗮𝘁𝘁𝗲𝗿𝘀: The best solutions eliminate unnecessary work. Simulation is O(n × max(tickets)). Math is O(n). 𝗖𝗼𝗱𝗲: https://lnkd.in/gn58Hcf7 𝗗𝗮𝘆 𝟲𝟴/𝟭𝟬𝟬 ✅ 𝟲𝟴 𝗱𝗼𝘄𝗻. 𝟯𝟮 𝘁𝗼 𝗴𝗼. #100DaysOfCode #LeetCode #Queue #Algorithms #MathematicalThinking #CodingInterview #Programming #Java #Optimization #LogicalThinking

To view or add a comment, sign in

Explore content categories