. Minimum Cost For Tickets
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

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

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

Undress AI Tool
Undress images for free

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)

Hot Topics

Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...
