search
HomeBackend DevelopmentPHP Tutorial. Minimum Cost For Tickets

. 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
  • 1
  • days is in strictly increasing order.
  • costs.length == 3
  • 1

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

  1. 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.
  2. 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]).
  3. Final Answer: After filling the DP array, the minimum cost will be stored in dp[365], which covers all possible travel days.

Plan

  1. Initialize an array dp[] of size 366 (one extra to handle up to day 365).
  2. Set dp[0] to 0, as there is no cost for day 0.
  3. Create a set travelDays to quickly check if a particular day is a travel day.
  4. 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.
  5. 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
?>

Explanation:

  • The algorithm iterates over each day of the year (365 days).
  • For each travel day, it computes the cost by considering whether it is cheaper to:
    • Buy a 1-day pass (adds the cost of the 1-day pass to the previous day's cost).
    • Buy a 7-day pass (adds the cost of the 7-day pass and considers the cost of traveling on the past 7 days).
    • Buy a 30-day pass (adds the cost of the 30-day pass and considers the cost of traveling over the past 30 days).
  • If it is not a travel day, the cost remains the same as the previous day.

Example Walkthrough

Example 1:

Input:

$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:

  • LinkedIn
  • 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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment