<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>time Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/time/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/time/</link>
	<description></description>
	<lastBuildDate>Sun, 03 Apr 2022 04:47:15 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.8</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>time Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/time/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 2224. Minimum Number of Operations to Convert Time</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-2224-minimum-number-of-operations-to-convert-time/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-2224-minimum-number-of-operations-to-convert-time/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 03 Apr 2022 04:46:31 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[time]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9617</guid>

					<description><![CDATA[<p>You are given two strings&#160;current&#160;and&#160;correct&#160;representing two&#160;24-hour times. 24-hour times are formatted as&#160;"HH:MM", where&#160;HH&#160;is between&#160;00&#160;and&#160;23, and&#160;MM&#160;is between&#160;00&#160;and&#160;59. The earliest 24-hour time is&#160;00:00, and the latest is&#160;23:59.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-2224-minimum-number-of-operations-to-convert-time/">花花酱 LeetCode 2224. Minimum Number of Operations to Convert Time</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>You are given two strings&nbsp;<code>current</code>&nbsp;and&nbsp;<code>correct</code>&nbsp;representing two&nbsp;<strong>24-hour times</strong>.</p>



<p>24-hour times are formatted as&nbsp;<code>"HH:MM"</code>, where&nbsp;<code>HH</code>&nbsp;is between&nbsp;<code>00</code>&nbsp;and&nbsp;<code>23</code>, and&nbsp;<code>MM</code>&nbsp;is between&nbsp;<code>00</code>&nbsp;and&nbsp;<code>59</code>. The earliest 24-hour time is&nbsp;<code>00:00</code>, and the latest is&nbsp;<code>23:59</code>.</p>



<p>In one operation you can increase the time&nbsp;<code>current</code>&nbsp;by&nbsp;<code>1</code>,&nbsp;<code>5</code>,&nbsp;<code>15</code>, or&nbsp;<code>60</code>&nbsp;minutes. You can perform this operation&nbsp;<strong>any</strong>&nbsp;number of times.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>minimum number of operations</strong>&nbsp;needed to convert&nbsp;</em><code>current</code><em>&nbsp;to&nbsp;</em><code>correct</code>.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> current = "02:30", correct = "04:35"
<strong>Output:</strong> 3
<strong>Explanation:
</strong>We can convert current to correct in 3 operations as follows:
- Add 60 minutes to current. current becomes "03:30".
- Add 60 minutes to current. current becomes "04:30".
- Add 5 minutes to current. current becomes "04:35".
It can be proven that it is not possible to convert current to correct in fewer than 3 operations.</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> current = "11:00", correct = "11:01"
<strong>Output:</strong> 1
<strong>Explanation:</strong> We only have to add one minute to current, so the minimum number of operations needed is 1.
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>current</code>&nbsp;and&nbsp;<code>correct</code>&nbsp;are in the format&nbsp;<code>"HH:MM"</code></li><li><code>current &lt;= correct</code></li></ul>



<h2><strong>Solution: Greedy</strong></h2>



<p>Start with 60, then 15, 5 and finally increase 1 minute a time.</p>



<p>Time complexity: O(1)<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int convertTime(string current, string correct) {
    auto getMinute = [](string_view t) {
      return (t[0] - '0') * 10 * 60 
             + (t[1] - '0') * 60 
             + (t[3] - '0') * 10 
             + (t[4] - '0');
    };
    
    int t1 = getMinute(current);
    int t2 = getMinute(correct);
    int ans = 0;    
    for (int d : {60, 15, 5, 1})
      while (t2 - t1 &gt;= d) {
        ++ans;
        t1 += d;
      }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-2224-minimum-number-of-operations-to-convert-time/">花花酱 LeetCode 2224. Minimum Number of Operations to Convert Time</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/greedy/leetcode-2224-minimum-number-of-operations-to-convert-time/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1904. The Number of Full Rounds You Have Played</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-1904-the-number-of-full-rounds-you-have-played/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-1904-the-number-of-full-rounds-you-have-played/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 15 Aug 2021 19:20:36 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[clock]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[time]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8584</guid>

					<description><![CDATA[<p>A new online video game has been released, and in this video game, there are&#160;15-minute&#160;rounds scheduled every&#160;quarter-hour&#160;period. This means that at&#160;HH:00,&#160;HH:15,&#160;HH:30&#160;and&#160;HH:45, a new round starts,&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1904-the-number-of-full-rounds-you-have-played/">花花酱 LeetCode 1904. The Number of Full Rounds You Have Played</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>A new online video game has been released, and in this video game, there are&nbsp;<strong>15-minute</strong>&nbsp;rounds scheduled every&nbsp;<strong>quarter-hour</strong>&nbsp;period. This means that at&nbsp;<code>HH:00</code>,&nbsp;<code>HH:15</code>,&nbsp;<code>HH:30</code>&nbsp;and&nbsp;<code>HH:45</code>, a new round starts, where&nbsp;<code>HH</code>&nbsp;represents an integer number from&nbsp;<code>00</code>&nbsp;to&nbsp;<code>23</code>. A&nbsp;<strong>24-hour clock</strong>&nbsp;is used, so the earliest time in the day is&nbsp;<code>00:00</code>&nbsp;and the latest is&nbsp;<code>23:59</code>.</p>



<p>Given two strings&nbsp;<code>startTime</code>&nbsp;and&nbsp;<code>finishTime</code>&nbsp;in the format&nbsp;<code>"HH:MM"</code>&nbsp;representing the exact time you&nbsp;<strong>started</strong>&nbsp;and&nbsp;<strong>finished</strong>&nbsp;playing the game, respectively, calculate the&nbsp;<strong>number of full rounds</strong>&nbsp;that you played during your game session.</p>



<ul><li>For example, if&nbsp;<code>startTime = "05:20"</code>&nbsp;and&nbsp;<code>finishTime = "05:59"</code>&nbsp;this means you played only one full round from&nbsp;<code>05:30</code>&nbsp;to&nbsp;<code>05:45</code>. You did not play the full round from&nbsp;<code>05:15</code>&nbsp;to&nbsp;<code>05:30</code>&nbsp;because you started after the round began, and you did not play the full round from&nbsp;<code>05:45</code>&nbsp;to&nbsp;<code>06:00</code>&nbsp;because you stopped before the round ended.</li></ul>



<p>If&nbsp;<code>finishTime</code>&nbsp;is&nbsp;<strong>earlier</strong>&nbsp;than&nbsp;<code>startTime</code>, this means you have played overnight (from&nbsp;<code>startTime</code>&nbsp;to the midnight and from midnight to&nbsp;<code>finishTime</code>).</p>



<p>Return&nbsp;<em>the&nbsp;<strong>number of full rounds</strong>&nbsp;that you have played if you had started playing at&nbsp;</em><code>startTime</code><em>&nbsp;and finished at&nbsp;</em><code>finishTime</code>.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> startTime = "12:01", finishTime = "12:44"
<strong>Output:</strong> 1
<strong>Explanation:</strong> You played one full round from 12:15 to 12:30.
You did not play the full round from 12:00 to 12:15 because you started playing at 12:01 after it began.
You did not play the full round from 12:30 to 12:45 because you stopped playing at 12:44 before it ended.
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> startTime = "20:00", finishTime = "06:00"
<strong>Output:</strong> 40
<strong>Explanation:</strong> You played 16 full rounds from 20:00 to 00:00 and 24 full rounds from 00:00 to 06:00.
16 + 24 = 40.
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> startTime = "00:00", finishTime = "23:59"
<strong>Output:</strong> 95
<strong>Explanation:</strong> You played 4 full rounds each hour except for the last hour where you played 3 full rounds.
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>startTime</code>&nbsp;and&nbsp;<code>finishTime</code>&nbsp;are in the format&nbsp;<code>HH:MM</code>.</li><li><code>00 &lt;= HH &lt;= 23</code></li><li><code>00 &lt;= MM &lt;= 59</code></li><li><code>startTime</code>&nbsp;and&nbsp;<code>finishTime</code>&nbsp;are not equal.</li></ul>



<h2><strong>Solution: String / Simple math</strong></h2>



<p>ans = max(0, floor(end / 15) &#8211; ceil(start / 15))</p>



<p>Tips: </p>



<ol><li>Write a reusable function to parse time to minutes.</li><li>a / b for floor, (a + b &#8211; 1) / b for ceil</li></ol>



<p>Time complexity: O(1)<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int numberOfRounds(string startTime, string finishTime) {
    auto parseTime = [](string t) {
      return ((t[0] - '0') * 10 + (t[1] - '0')) * 60 + (t[3] - '0') * 10 + t[4] - '0';
    };
    int m1 = parseTime(startTime);
    int m2 = parseTime(finishTime);
    if (m2 &lt; m1) m2 += 24 * 60;
    return max(0, m2 / 15 - (m1 + 14) / 15);
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1904-the-number-of-full-rounds-you-have-played/">花花酱 LeetCode 1904. The Number of Full Rounds You Have Played</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-1904-the-number-of-full-rounds-you-have-played/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1701. Average Waiting Time</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-1701-average-waiting-time/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-1701-average-waiting-time/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 27 Dec 2020 01:11:00 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[queue]]></category>
		<category><![CDATA[time]]></category>
		<category><![CDATA[waiting]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7843</guid>

					<description><![CDATA[<p>There is a restaurant with a single chef. You are given an array&#160;customers, where&#160;customers[i] = [arrivali, timei]: arrivali&#160;is the arrival time of the&#160;ith&#160;customer. The arrival&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-1701-average-waiting-time/">花花酱 LeetCode 1701. Average Waiting Time</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>There is a restaurant with a single chef. You are given an array&nbsp;<code>customers</code>, where&nbsp;<code>customers[i] = [arrival<sub>i</sub>, time<sub>i</sub>]:</code></p>



<ul><li><code>arrival<sub>i</sub></code>&nbsp;is the arrival time of the&nbsp;<code>i<sup>th</sup></code>&nbsp;customer. The arrival times are sorted in&nbsp;<strong>non-decreasing</strong>&nbsp;order.</li><li><code>time<sub>i</sub></code>&nbsp;is the time needed to prepare the order of the&nbsp;<code>i<sup>th</sup></code>&nbsp;customer.</li></ul>



<p>When a customer arrives, he gives the chef his order, and the chef starts preparing it once he is idle. The customer waits till the chef finishes preparing his order. The chef does not prepare food for more than one customer at a time. The chef prepares food for customers&nbsp;<strong>in the order they were given in the input</strong>.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>average</strong>&nbsp;waiting time of all customers</em>. Solutions within&nbsp;<code>10<sup>-5</sup></code>&nbsp;from the actual answer are considered accepted.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> customers = [[1,2],[2,5],[4,3]]
<strong>Output:</strong> 5.00000
<strong>Explanation:
</strong>1) The first customer arrives at time 1, the chef takes his order and starts preparing it immediately at time 1, and finishes at time 3, so the waiting time of the first customer is 3 - 1 = 2.
2) The second customer arrives at time 2, the chef takes his order and starts preparing it at time 3, and finishes at time 8, so the waiting time of the second customer is 8 - 2 = 6.
3) The third customer arrives at time 4, the chef takes his order and starts preparing it at time 8, and finishes at time 11, so the waiting time of the third customer is 11 - 4 = 7.
So the average waiting time = (2 + 6 + 7) / 3 = 5.
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> customers = [[5,2],[5,4],[10,3],[20,1]]
<strong>Output:</strong> 3.25000
<strong>Explanation:
</strong>1) The first customer arrives at time 5, the chef takes his order and starts preparing it immediately at time 5, and finishes at time 7, so the waiting time of the first customer is 7 - 5 = 2.
2) The second customer arrives at time 5, the chef takes his order and starts preparing it at time 7, and finishes at time 11, so the waiting time of the second customer is 11 - 5 = 6.
3) The third customer arrives at time 10, the chef takes his order and starts preparing it at time 11, and finishes at time 14, so the waiting time of the third customer is 14 - 10 = 4.
4) The fourth customer arrives at time 20, the chef takes his order and starts preparing it immediately at time 20, and finishes at time 21, so the waiting time of the fourth customer is 21 - 20 = 1.
So the average waiting time = (2 + 6 + 4 + 1) / 4 = 3.25.
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= customers.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= arrival<sub>i</sub>, time<sub>i</sub>&nbsp;&lt;= 10<sup>4</sup></code></li><li><code>arrival<sub>i&nbsp;</sub>&lt;= arrival<sub>i+1</sub></code></li></ul>



<h2><strong>Solution: Simulation</strong></h2>



<p>When a customer arrives, if the arrival time is greater than current, then advance the clock to arrival time. Advance the clock by cooking time. Waiting time  = current time &#8211; arrival time.</p>



<p>Time complexity: O(n)<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  double averageWaitingTime(vector&lt;vector&lt;int&gt;&gt;&amp; customers) {
    int t = 0;
    double w = 0;
    for (const auto&amp; c : customers) {
      if (c[0] &gt; t) t = c[0];
      t += c[1];
      w += t - c[0];
    }
    return w / customers.size();
  }
};</pre>

</div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def averageWaitingTime(self, customers: List[List[int]]) -&gt; float:
    cur = 0
    waiting = 0
    for arrival, time in customers:
      cur = max(cur, arrival) + time
      waiting += cur - arrival
    return waiting / len(customers)</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-1701-average-waiting-time/">花花酱 LeetCode 1701. Average Waiting Time</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/simulation/leetcode-1701-average-waiting-time/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 539. Minimum Time Difference</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-539-minimum-time-difference/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-539-minimum-time-difference/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 22 Mar 2018 04:51:03 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[clock]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[time]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=2279</guid>

					<description><![CDATA[<p>Problem Given a list of 24-hour clock time points in &#8220;Hour:Minutes&#8221; format, find the minimum minutes difference between any two time points in the list. Example 1:&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-539-minimum-time-difference/">花花酱 LeetCode 539. Minimum Time Difference</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p>Given a list of 24-hour clock time points in &#8220;Hour:Minutes&#8221; format, find the minimum <b>minutes</b> difference between any two time points in the list.</p>
<p><b>Example 1:</b></p>
<pre class="crayon:false"><b>Input:</b> ["23:59","00:00"]
<b>Output:</b> 1
</pre>
<p><b>Note:</b></p>
<ol>
<li>The number of time points in the given list is at least 2 and won&#8217;t exceed 20000.</li>
<li>The input time is legal and ranges from 00:00 to 23:59.</li>
</ol>
<h1><strong>Solution</strong></h1>
<p>Time complexity: O(nlog1440)</p>
<p>Space complexity: O(n)</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: huahua
// Running time: 16 ms
class Solution {
public:
  int findMinDifference(vector&lt;string&gt;&amp; timePoints) {    
    constexpr int kMins = 24 * 60;
    set&lt;int&gt; seen;    
    for (const string&amp; time : timePoints) {
      int m = stoi(time.substr(0, 2)) * 60 + stoi(time.substr(3));
      if (!seen.insert(m).second) return 0;
    }
    
    int ans = (*seen.begin() - *seen.rbegin() + kMins) % kMins;
    const int* l = nullptr;
    for (const int&amp; t : seen) {
      if (l) ans = min(ans, t - *l);
      l = &amp;t;
    }
    return ans;
  }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-539-minimum-time-difference/">花花酱 LeetCode 539. Minimum Time Difference</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-539-minimum-time-difference/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 309. Best Time to Buy and Sell Stock with Cooldown</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-309-best-time-to-buy-and-sell-stock-with-cooldown/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-309-best-time-to-buy-and-sell-stock-with-cooldown/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 06 Jan 2018 18:57:32 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[profit]]></category>
		<category><![CDATA[stock]]></category>
		<category><![CDATA[time]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1517</guid>

					<description><![CDATA[<p>题目大意：给你每天的股价，没有交易次数限制，但是卖出后要休息一天才能再买进。问你最大收益是多少？ Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-309-best-time-to-buy-and-sell-stock-with-cooldown/">花花酱 LeetCode 309. Best Time to Buy and Sell Stock with Cooldown</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe width="500" height="375" src="https://www.youtube.com/embed/oL6mRyTn56M?feature=oembed" frameborder="0" gesture="media" allow="encrypted-media" allowfullscreen></iframe></p>
<p>题目大意：给你每天的股价，没有交易次数限制，但是卖出后要休息一天才能再买进。问你最大收益是多少？</p>
<p>Say you have an array for which the <i>i</i><sup>th</sup> element is the price of a given stock on day <i>i</i>.</p>
<p>Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:</p>
<ul>
<li>You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).</li>
<li>After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)</li>
</ul>
<p><b>Example:</b></p><pre class="crayon-plain-tag">prices = [1, 2, 3, 0, 2]
maxProfit = 3
transactions = [buy, sell, cooldown, buy, sell]</pre><p><strong>Idea:</strong></p>
<p>DP</p>
<p><img class="alignnone size-full wp-image-1522" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/309-ep150.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/309-ep150.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/309-ep150-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/309-ep150-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<p><strong>Solution:</strong></p>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(1)</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 12 ms
class Solution {
public:
    int maxProfit(vector&lt;int&gt;&amp; prices) {
        int sold = 0;
        int rest = 0;
        int hold = INT_MIN;
        for (const int price : prices) {
            int prev_sold = sold;
            sold = hold + price;
            hold = max(hold, rest - price);
            rest = max(rest, prev_sold);
        }
        return max(rest, sold);
    }
};</pre><p><strong>Related Problems:</strong></p>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/dynamic-programming/leetcode-121-best-time-to-buy-and-sell-stock/">花花酱 LeetCode 121. Best Time to Buy and Sell Stock</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-309-best-time-to-buy-and-sell-stock-with-cooldown/">花花酱 LeetCode 309. Best Time to Buy and Sell Stock with Cooldown</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-309-best-time-to-buy-and-sell-stock-with-cooldown/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 681. Next Closest Time</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-681-next-closest-time/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-681-next-closest-time/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 25 Sep 2017 04:01:14 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[brute force]]></category>
		<category><![CDATA[clock]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[time]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=403</guid>

					<description><![CDATA[<p>Problem: https://leetcode.com/problems/next-closest-time/description/ no limit on how many times a digit can be reused. You may assume the given input string is always valid. For example,&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-681-next-closest-time/">花花酱 LeetCode 681. Next Closest Time</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe width="500" height="375" src="https://www.youtube.com/embed/IAet94C1FCc?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<h1><strong>Problem:</strong></h1>
<p><a href="https://leetcode.com/problems/next-closest-time/description/">https://leetcode.com/problems/next-closest-time/description/</a><br />
no limit on how many times a digit can be reused.</p>
<p>You may assume the given input string is always valid. For example, &#8220;01:34&#8221;, &#8220;12:09&#8221; are all valid. &#8220;1:34&#8221;, &#8220;12:9&#8221; are all invalid.</p>
<h2><b>Example 1:</b></h2>
<pre class="crayon:false">Input: "19:34"
Output: "19:39"
Explanation: The next closest time choosing from digits 1, 9, 3, 4, is 19:39, 
which occurs 5 minutes later.  
It is not 19:33, because this occurs 23 hours and 59 minutes later.
</pre>
<h2><b>Example 2:</b></h2>
<pre class="crayon:false">Input: "23:59"
Output: "22:22"
Explanation: The next closest time choosing from digits 2, 3, 5, 9, is 22:22. 
It may be assumed that the returned time is next day's time since it is smaller 
than the input time numerically.</pre>
<p>Ads<br />
<ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-2404451723245401" data-ad-slot="7983117522"></ins></p>
<h1><strong>Solution1: Brute force</strong></h1>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 3 ms
class Solution {
public:
    string nextClosestTime(string time) {
        set&lt;char&gt; s(time.begin(), time.end());
        int hour = stoi(time.substr(0, 2));
        int min = stoi(time.substr(3, 2));
        while (true) {
            if (++min == 60) {
                min = 0;
                (++hour) %= 24;                
            }
            char buffer[5];
            sprintf(buffer, "%02d:%02d", hour, min);
            set&lt;char&gt; s2(buffer, buffer + sizeof(buffer));
            if (includes(s.begin(), s.end(), s2.begin(), s2.end()))
                return string(buffer);
        }
        return time;
    }
};</pre><p></div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 85 ms
class Solution {
    public String nextClosestTime(String time) {
        int hour = Integer.parseInt(time.substring(0, 2));
        int min = Integer.parseInt(time.substring(3, 5));
        while (true) {            
            if (++min == 60) {
                min = 0;
                ++hour;
                hour %= 24;
            }
            String curr = String.format("%02d:%02d", hour, min);
            Boolean valid = true;
            for (int i = 0; i &lt; curr.length(); ++i)
                if (time.indexOf(curr.charAt(i)) &lt; 0) {
                    valid = false;
                    break;
                }
            if (valid) return curr;
        }
    }
}</pre><p></div><h2 class="tabtitle">Python</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 65 ms
"""
class Solution:
    def nextClosestTime(self, time):        
        s = set(time)
        hour = int(time[0:2])
        minute = int(time[3:5])
        while True:
            minute += 1
            if minute == 60:
                minute = 0
                hour = 0 if hour == 23 else hour + 1
            
            time = "%02d:%02d" % (hour, minute)
            if set(time) &lt;= s:
                return time
        return time</pre><p></div></div></p>
<h1><strong>Solution 2: DFS</strong></h1>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua 
// Running time: 3 ms
class Solution {
public:
    string nextClosestTime(string time) {
        vector&lt;int&gt; d = {
            time[0] - '0', time[1] - '0', time[3] - '0', time[4] - '0' };
        
        int h = d[0] * 10 + d[1];
        int m = d[2] * 10 + d[3];
        vector&lt;int&gt; curr(4, 0);
        int now = toTime(h, m);
        int best = now;
        
        dfs(0, d, curr, now, best);
        char buff[5];
        sprintf(buff, "%02d:%02d", best / 60, best % 60);
        return string(buff);
    }
private:
    void dfs(int dep, const vector&lt;int&gt;&amp; digits, vector&lt;int&gt;&amp; curr, int time, int&amp; best) {
        if (dep == 4) {
            int curr_h = curr[0] * 10 + curr[1];
            int curr_m = curr[2] * 10 + curr[3];
            if (curr_h &gt; 23 || curr_m &gt; 59) return;
            int curr_time = toTime(curr_h, curr_m);
            if (timeDiff(time, curr_time) &lt; timeDiff(time, best))
                best = curr_time;
            return;
        }            
        
        for (int digit : digits) {
            curr[dep] = digit;
            dfs(dep + 1, digits, curr, time, best);
        }        
    }
    
    int toTime(int h, int m) {
        return h * 60 + m;
    }
    
    int timeDiff(int t1, int t2) {
        if (t1 == t2) return INT_MAX;
        return ((t2 - t1) + 24 * 60) % (24 * 60);
    }
};</pre><p></div></div></p>
<h1><strong>Solution 3: Brute force + Time library</strong></h1>
<p><div class="responsive-tabs">
<h2 class="tabtitle">Python3</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 292 ms
"""
from datetime import *
class Solution:
    def nextClosestTime(self, time):        
        s = set(time)        
        while True:
            time = (datetime.strptime(time, '%H:%M') + 
                    timedelta(minutes=1)).strftime('%H:%M')
            if set(time) &lt;= s: 
                return time
        return time</pre><p></div></div></p>
<h1>Related Problems:</h1>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/bit/leetcode-401-binary-watch/">花花酱 LeetCode 401. Binary Watch</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-681-next-closest-time/">花花酱 LeetCode 681. Next Closest Time</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/simulation/leetcode-681-next-closest-time/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
