983. Minimum Cost For Tickets
Difficulty: Medium
Topics: Array, Dynamic Programming
You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array days. Each day is an integer from 1 to 365.
Train tickets are sold in three different ways:
- a 1-day pass is sold for costs[0] dollars,
- a 7-day pass is sold for costs[1] dollars, and
- a 30-day pass is sold for costs[2] dollars.
The passes allow that many days of consecutive travel.
- For example, if we get a 7-day pass on day 2, then we can travel for 7 days: 2, 3, 4, 5, 6, 7, and 8.
Return the minimum number of dollars you need to travel every day in the given list of days.
Example 1:
- Input: days = [1,4,6,7,8,20], costs = [2,7,15]
- Output: 11
-
Explanation: For example, here is one way to buy passes that lets you travel your travel plan:
- On day 1, you bought a 1-day pass for costs[0] = $2, which covered day 1.
- On day 3, you bought a 7-day pass for costs[1] = $7, which covered days 3, 4, ..., 9.
- On day 20, you bought a 1-day pass for costs[0] = $2, which covered day 20.
- In total, you spent $11 and covered all the days of your travel.
Example 2:
- Input: days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15]
- Output: 17
-
Explanation: For example, here is one way to buy passes that lets you travel your travel plan:
- On day 1, you bought a 30-day pass for costs[2] = $15 which covered days 1, 2, ..., 30.
- On day 31, you bought a 1-day pass for costs[0] = $2 which covered day 31.
- In total, you spent $17 and covered all the days of your travel.
Constraints:
- 1 <= days.length <= 365
- 1 <= days[i] <= 365
- days is in strictly increasing order.
- costs.length == 3
- 1 <= costs[i] <= 1000
Solution:
The problem involves determining the minimum cost to travel on a set of specified days throughout the year. The problem offers three types of travel passes: 1-day, 7-day, and 30-day passes, each with specific costs. The goal is to find the cheapest way to cover all travel days using these passes. The task requires using dynamic programming to efficiently calculate the minimal cost.
Key Points
- Dynamic Programming (DP): We are using dynamic programming to keep track of the minimum cost for each day.
- Travel Days: The travel days are provided in strictly increasing order, meaning we know exactly which days we need to travel.
-
Three Types of Passes: For each day d in the days array, calculate the minimum cost by considering the cost of buying a pass that covers the current day d:
- 1-day pass: The cost would be the cost of the 1-day pass (costs[0]) added to the cost of the previous day (dp[i-1]).
- 7-day pass: The cost would be the cost of the 7-day pass (costs[1]) added to the cost of the most recent day that is within 7 days of d.
- 30-day pass: The cost would be the cost of the 30-day pass (costs[2]) added to the cost of the most recent day that is within 30 days of d.
- Base Case: The minimum cost for a day when no travel is done is 0.
Approach
- DP Array: We'll use a DP array dp[] where dp[i] represents the minimum cost to cover all travel days up to day i.
-
Filling the DP Array: For each day from 1 to 365:
- If the day is a travel day, we calculate the minimum cost by considering:
- The cost of using a 1-day pass.
- The cost of using a 7-day pass.
- The cost of using a 30-day pass.
- If the day is not a travel day, the cost for that day will be the same as the previous day (dp[i] = dp[i-1]).
- If the day is a travel day, we calculate the minimum cost by considering:
- Final Answer: After filling the DP array, the minimum cost will be stored in dp[365], which covers all possible travel days.
Plan
- Initialize an array dp[] of size 366 (one extra to handle up to day 365).
- Set dp[0] to 0, as there is no cost for day 0.
- Create a set travelDays to quickly check if a particular day is a travel day.
- Iterate through each day from 1 to 365:
- If it is a travel day, compute the minimum cost by considering each type of pass.
- If not, carry over the previous day's cost.
- Return the value at dp[365].
Let's implement this solution in PHP: 983. Minimum Cost For Tickets
<?php /** * @param Integer[] $days * @param Integer[] $costs * @return Integer */ function mincostTickets($days, $costs) { ... ... ... /** * go to ./solution.php */ } // Example usage: $days1 = [1, 4, 6, 7, 8, 20]; $costs1 = [2, 7, 15]; echo mincostTickets($days1, $costs1); // Output: 11 $days2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31]; $costs2 = [2, 7, 15]; echo mincostTickets($days2, $costs2); // Output: 17 ?> <h3> Explanation: </h3> <ul> <li>The algorithm iterates over each day of the year (365 days).</li> <li>For each travel day, it computes the cost by considering whether it is cheaper to: <ul> <li>Buy a 1-day pass (adds the cost of the 1-day pass to the previous day's cost).</li> <li>Buy a 7-day pass (adds the cost of the 7-day pass and considers the cost of traveling on the past 7 days).</li> <li>Buy a 30-day pass (adds the cost of the 30-day pass and considers the cost of traveling over the past 30 days).</li> </ul> </li> <li>If it is not a travel day, the cost remains the same as the previous day.</li> </ul> <h3> Example Walkthrough </h3> <h4> Example 1: </h4> <p><strong>Input:</strong><br> </p> <pre class="brush:php;toolbar:false">$days = [1, 4, 6, 7, 8, 20]; $costs = [2, 7, 15];
- Day 1: Buy a 1-day pass for $2.
- Day 4: Buy a 7-day pass for $7 (cover days 4 to 9).
- Day 20: Buy another 1-day pass for $2.
Total cost = $2 $7 $2 = $11.
Example 2:
Input:
$days = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31]; $costs = [2, 7, 15];
- Day 1: Buy a 30-day pass for $15 (cover days 1 to 30).
- Day 31: Buy a 1-day pass for $2.
Total cost = $15 $2 = $17.
Time Complexity
The time complexity of the solution is O(365), as we are iterating through all days of the year, and for each day, we perform constant time operations (checking travel days and updating the DP array). Thus, the solution runs in linear time relative to the number of days.
Output for Example
Example 1:
$days = [1, 4, 6, 7, 8, 20]; $costs = [2, 7, 15]; echo mincostTickets($days, $costs); // Output: 11
Example 2:
$days = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31]; $costs = [2, 7, 15]; echo mincostTickets($days, $costs); // Output: 17
The solution efficiently calculates the minimum cost of covering the travel days using dynamic programming. By iterating over the days and considering all possible passes (1-day, 7-day, 30-day), the algorithm finds the optimal strategy for purchasing the passes. The time complexity is linear in terms of the number of days, making it suitable for the problem constraints.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
- GitHub
The above is the detailed content of . Minimum Cost For Tickets. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

In PHP, you can use square brackets or curly braces to obtain string specific index characters, but square brackets are recommended; the index starts from 0, and the access outside the range returns a null value and cannot be assigned a value; mb_substr is required to handle multi-byte characters. For example: $str="hello";echo$str[0]; output h; and Chinese characters such as mb_substr($str,1,1) need to obtain the correct result; in actual applications, the length of the string should be checked before looping, dynamic strings need to be verified for validity, and multilingual projects recommend using multi-byte security functions uniformly.

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech
