国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Backend Development PHP Tutorial . Minimum Cost For Tickets

. Minimum Cost For Tickets

Jan 01, 2025 am 08:28 AM

. 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

  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
?>




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

  • 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 of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are some best practices for versioning a PHP-based API? What are some best practices for versioning a PHP-based API? Jun 14, 2025 am 12:27 AM

ToversionaPHP-basedAPIeffectively,useURL-basedversioningforclarityandeaseofrouting,separateversionedcodetoavoidconflicts,deprecateoldversionswithclearcommunication,andconsidercustomheadersonlywhennecessary.StartbyplacingtheversionintheURL(e.g.,/api/v

How do I implement authentication and authorization in PHP? How do I implement authentication and authorization in PHP? Jun 20, 2025 am 01:03 AM

TosecurelyhandleauthenticationandauthorizationinPHP,followthesesteps:1.Alwayshashpasswordswithpassword_hash()andverifyusingpassword_verify(),usepreparedstatementstopreventSQLinjection,andstoreuserdatain$_SESSIONafterlogin.2.Implementrole-basedaccessc

What are the differences between procedural and object-oriented programming paradigms in PHP? What are the differences between procedural and object-oriented programming paradigms in PHP? Jun 14, 2025 am 12:25 AM

Proceduralandobject-orientedprogramming(OOP)inPHPdiffersignificantlyinstructure,reusability,anddatahandling.1.Proceduralprogrammingusesfunctionsorganizedsequentially,suitableforsmallscripts.2.OOPorganizescodeintoclassesandobjects,modelingreal-worlden

What are weak references (WeakMap) in PHP, and when might they be useful? What are weak references (WeakMap) in PHP, and when might they be useful? Jun 14, 2025 am 12:25 AM

PHPdoesnothaveabuilt-inWeakMapbutoffersWeakReferenceforsimilarfunctionality.1.WeakReferenceallowsholdingreferenceswithoutpreventinggarbagecollection.2.Itisusefulforcaching,eventlisteners,andmetadatawithoutaffectingobjectlifecycles.3.YoucansimulateaWe

How can you handle file uploads securely in PHP? How can you handle file uploads securely in PHP? Jun 19, 2025 am 01:05 AM

To safely handle file uploads in PHP, the core is to verify file types, rename files, and restrict permissions. 1. Use finfo_file() to check the real MIME type, and only specific types such as image/jpeg are allowed; 2. Use uniqid() to generate random file names and store them in non-Web root directory; 3. Limit file size through php.ini and HTML forms, and set directory permissions to 0755; 4. Use ClamAV to scan malware to enhance security. These steps effectively prevent security vulnerabilities and ensure that the file upload process is safe and reliable.

What are the differences between == (loose comparison) and === (strict comparison) in PHP? What are the differences between == (loose comparison) and === (strict comparison) in PHP? Jun 19, 2025 am 01:07 AM

In PHP, the main difference between == and == is the strictness of type checking. ==Type conversion will be performed before comparison, for example, 5=="5" returns true, and ===Request that the value and type are the same before true will be returned, for example, 5==="5" returns false. In usage scenarios, === is more secure and should be used first, and == is only used when type conversion is required.

How can you interact with NoSQL databases (e.g., MongoDB, Redis) from PHP? How can you interact with NoSQL databases (e.g., MongoDB, Redis) from PHP? Jun 19, 2025 am 01:07 AM

Yes, PHP can interact with NoSQL databases like MongoDB and Redis through specific extensions or libraries. First, use the MongoDBPHP driver (installed through PECL or Composer) to create client instances and operate databases and collections, supporting insertion, query, aggregation and other operations; second, use the Predis library or phpredis extension to connect to Redis, perform key-value settings and acquisitions, and recommend phpredis for high-performance scenarios, while Predis is convenient for rapid deployment; both are suitable for production environments and are well-documented.

How do I perform arithmetic operations in PHP ( , -, *, /, %)? How do I perform arithmetic operations in PHP ( , -, *, /, %)? Jun 19, 2025 pm 05:13 PM

The methods of using basic mathematical operations in PHP are as follows: 1. Addition signs support integers and floating-point numbers, and can also be used for variables. String numbers will be automatically converted but not recommended to dependencies; 2. Subtraction signs use - signs, variables are the same, and type conversion is also applicable; 3. Multiplication signs use * signs, which are suitable for numbers and similar strings; 4. Division uses / signs, which need to avoid dividing by zero, and note that the result may be floating-point numbers; 5. Taking the modulus signs can be used to judge odd and even numbers, and when processing negative numbers, the remainder signs are consistent with the dividend. The key to using these operators correctly is to ensure that the data types are clear and the boundary situation is handled well.

See all articles