<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by HAOYU LEI on Medium]]></title>
        <description><![CDATA[Stories by HAOYU LEI on Medium]]></description>
        <link>https://medium.com/@hylei_73413?source=rss-e04cea65fd51------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Y8qDrSOHHztw6WoM</url>
            <title>Stories by HAOYU LEI on Medium</title>
            <link>https://medium.com/@hylei_73413?source=rss-e04cea65fd51------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 05:22:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hylei_73413/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to align accounting signals with market return data? An example with SQL code]]></title>
            <link>https://medium.com/@hylei_73413/how-to-align-accounting-signals-with-market-return-data-an-example-with-sql-code-b13792e1566e?source=rss-e04cea65fd51------2</link>
            <guid isPermaLink="false">https://medium.com/p/b13792e1566e</guid>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[quantitative-strategies]]></category>
            <category><![CDATA[asset-pricing]]></category>
            <category><![CDATA[portfolio-management]]></category>
            <dc:creator><![CDATA[HAOYU LEI]]></dc:creator>
            <pubDate>Fri, 21 Feb 2020 08:14:08 GMT</pubDate>
            <atom:updated>2020-02-21T08:42:48.163Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aM5CJaEcGzmqfLBDakCI4w.png" /></figure><p>The key takeaway: if your table has millions of records, by all means avoid nested SQL queries; use group by + inner join instead.</p><p>In portfolio sorts, we occasionally find ourselves in the following situation:</p><blockquote>We have a <strong>return table A</strong> with headers:<br>| ID | date| return |</blockquote><blockquote>and an <strong>accounting signal table B</strong> with headers:<br>| ID | datadate| signal |</blockquote><blockquote>Without loss of generality we might assume returns are in monthly frequency, and accounting signals are in quarterly frequency. We would like to construct monthly-rebalanced portfolios according to, say, the latest signals 1-month away. The question arises: <strong>how should we merge the two tables?</strong></blockquote><p>Almost immediately one can think of the following nested subquery:</p><pre>CREATE TABLE mergedtable AS<br>SELECT a.ID, a.date, a.return, b.datadate, b.signal<br>FROM A as a, B as b<br>WHERE a.ID = b.ID and b.datadate = (<br>      SELECT max(datadate) as datadate<br>      FROM B as c<br>      WHERE a.ID = c.ID AND intck(&#39;month&#39;, c.datadate, a.date)&gt;=1<br>);</pre><p>intck is a SAS function which returns the number of months between two dates. You can find similar functions in other variants of SQL.</p><p>The major idea is: for each record in A, we want to find the latest record in B that satisfies the 1-month minimum lag criteria. It works for a small sample with a few thousands of observations, but the time increases dramatically once the sample size scales up to millions. In fact, it takes over a night to run the code on a 3-million-record A and a .8-million-record B.</p><p>So what’s next?</p><p>We can break the nested query into a group by and an inner join statement:</p><pre>CREATE TABLE mergedtable AS<br>SELECT a.ID, a.date, a.return, b.datadate, b.signal<br>FROM A as a inner join B as b<br>WHERE a.ID = b.ID AND intck(&#39;month&#39;, b.datadate, a.date)&gt;=1<br>GROUP BY a.ID, a.date<br>HAVING b.datadate=max(b.datadate);</pre><p>It reduces the processing time above million-record case to within tens of seconds.</p><p>So it is worth a recap that might save hours of waiting: use group by + inner join instead of nested queries.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b13792e1566e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 105 & 105. Reconstruct Trees Using Traversal Order]]></title>
            <link>https://medium.com/@hylei_73413/leetcode-105-105-reconstruct-trees-using-traversal-order-5b29046673ff?source=rss-e04cea65fd51------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b29046673ff</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[trees]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[HAOYU LEI]]></dc:creator>
            <pubDate>Wed, 26 Dec 2018 13:00:54 GMT</pubDate>
            <atom:updated>2018-12-26T13:00:54.483Z</atom:updated>
            <content:encoded><![CDATA[<p>Links:</p><ul><li><a href="https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal">Construct Binary Tree from Preorder and Inorder Traversal - LeetCode</a></li><li><a href="https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal">Construct Binary Tree from Inorder and Postorder Traversal - LeetCode</a></li></ul><p><strong>Question: </strong>Can we reconstruct binary trees using in-order/pre-order/post-order traversal? How can this be achieved?</p><p><strong>Answer</strong>: We can use in-order traversal, as well as either one of the rest two to achieve this. Why?</p><p>Suppose we are at the root of a tree, and we would like to traverse the whole tree. The traversal sequences can be represented as the following:</p><p>inorder = [inorder_left, root, inorder_right],</p><p>preorder = [root, preorder_left, preorder_right],</p><p>postorder = [postorder_left, postorder_right, root],</p><p>where inorder/preorder/postorder_left/right are list of nodes that are traversed according to respective traversal rules, and respective subtrees.</p><p>Observe the three sequences. We should note that whichever traversal rules we choose, the total number of nodes in a tree is constant. Therefore, we have the following important properties:</p><p>inorder_left = preorder_left = postorder_left,</p><p>inorder_right = preorder_right = postorder_right.</p><p>So long as we can separate nodes in the left and right subtrees, we are done, because this procedure can thus be recursively applied until the base case, where there is no node in the lists and the corresponding tree is empty. To achieve this we need two kinds of information, corresponding to two questions:</p><ol><li>What is the root?</li><li>What are the left and right subtrees?</li></ol><p>To get the answer to the first question, we need either preorder, or postorder traversal. Once we get the root, we can use it to interrogate the inorder traversal sequence and classify nodes in the left or right subtree.</p><p><strong>The last question</strong>: Can we use pre-order and post-order traversal sequence to reconstruct a binary tree?</p><p><strong>Answer</strong>: No, because there will be no way for us to tell between the nodes in the left and the right subtrees; they are mixed together.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b29046673ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Summary of ECON2280]]></title>
            <link>https://medium.com/@hylei_73413/summary-of-econ2280-d3908e59b681?source=rss-e04cea65fd51------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3908e59b681</guid>
            <category><![CDATA[econometrics]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[HAOYU LEI]]></dc:creator>
            <pubDate>Wed, 19 Dec 2018 13:52:39 GMT</pubDate>
            <atom:updated>2019-01-18T18:04:54.668Z</atom:updated>
            <content:encoded><![CDATA[<h3>ECON2280 Summary: Introductory Econometrics</h3><p>Link: <a href="https://i.cs.hku.hk/~hylei/econ2280/ECON2280_Revision.pdf">https://i.cs.hku.hk/~hylei/econ2280/ECON2280_Revision.pdf</a></p><h3>Tests</h3><p><strong>Chapter 4. Multiple Regression Analysis: Inference</strong></p><ul><li>The t-test: Test hypotheses about a <em>single</em> population parameter. Assumes estimators follow t-distribution, with df = n — k — 1.</li><li>p-value: p = P(|T| &gt; |t|).</li><li>Confidence intervals: 1. Find critical value c; 2. Calculate c * se(beta_hat); 3. The boundaries of CI are thus beta_hat +/- c * se(beta_hat).</li><li>The F-test: Test <em>multiple</em> linear restrictions. 1. Regression of unrestricted model: Rsq_ur, n, k; 2. Regression of restricted model: move restricted terms to the left of the equation and then regress: Rsq_r, q; 3. Compute <em>F</em> statistic: F = [(Rsq_ur — Rsq_r) / q] / [(1 — Rsq_ur)/(n-k-1)]; 4. Finally, determine critical value, using df_1 = q and df_2 = n — k — 1, and compare with the computed <em>F</em> statistic.</li></ul><p><strong>Chapter 7. Multiple Regression Analysis with Qualitative Information (7.1 — 7.4)</strong></p><ul><li>Traditional Chow Test. Null hypothesis: allows for no differences at all between the groups, i.e., delta_0 = delta_1 = … = delta_n= 0. In more cases, it is more interesting to allow for an <em>intercept</em> difference between the groups and then test for slope differences, i.e., delta_0 is ignored in the null hypothesis.</li></ul><p><strong>Chapter 8. Heteroskedasticity (8.1 – 8.4)</strong></p><p>Methods to check heteroskedasticity:</p><ul><li>The graphical method: plot squared residuals against independent variables</li><li>The Breusch — Pagan test for heteroskedasticity (BP Test). Assume u_hat^2 is a linear combination of all independent variables. The null hypothesis assumes the coefficients before all independent variables to be zero, i.e., delta_1 = ... = delta_k = 0. Compute either <em>F</em> statistic or the <em>LM</em> statistic: <em>LM </em>= n * R²_uhat, which follows a chi-squared distribution with df = k.</li><li>The White test for heteroskedasticity. Assume u_hat^2 is a linear combination of all independent variables, their squares, and their interactions. Alternatively, the form can be replaced with assuming u_hat^2 to be a linear combination of y_hat and y_hat^2. The null hypothesis is delta_1 = ... = delta_(2k + kC2), and delta_1 = delta_2 = 0 for the second.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3908e59b681" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Naïve Thoughts when Reviewing Econometrics]]></title>
            <link>https://medium.com/@hylei_73413/na%C3%AFve-thoughts-when-reviewing-econometrics-56ff897f43db?source=rss-e04cea65fd51------2</link>
            <guid isPermaLink="false">https://medium.com/p/56ff897f43db</guid>
            <category><![CDATA[econometrics]]></category>
            <dc:creator><![CDATA[HAOYU LEI]]></dc:creator>
            <pubDate>Fri, 14 Dec 2018 09:53:12 GMT</pubDate>
            <atom:updated>2018-12-14T09:53:12.884Z</atom:updated>
            <content:encoded><![CDATA[<ul><li>Math and Stats are techniques. Techniques are important, but it’s even more important to know how to <em>interpret</em> the results after applying them, e.g., regression. What do the coefficients mean? At which level of confidence can we declare the estimates to be correct? How do the results agree/disagree with our intuition? We need contexts. Contexts are what make econometrics different from Math and Stats; otherwise it makes no sense to make econometrics an independent subject.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56ff897f43db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 322. Coin Change]]></title>
            <link>https://medium.com/@hylei_73413/322-coin-change-d6dcf16d93cb?source=rss-e04cea65fd51------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6dcf16d93cb</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[dynamic-programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[HAOYU LEI]]></dc:creator>
            <pubDate>Mon, 10 Sep 2018 07:07:57 GMT</pubDate>
            <atom:updated>2018-12-26T13:01:26.876Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://leetcode.com/problems/coin-change/description/">LeetCode - The World&#39;s Leading Online Programming Learning Platform</a></p><blockquote>You are given coins of different denominations and a total amount of money <em>amount</em>. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.</blockquote><pre>class Solution {<br>    public int coinChange(int[] coins, int amount) {<br>        int len = coins.length;<br>        if (len == 0) return -1;<br>        int[] count = new int[amount + 1];<br>        for (int i = 0; i &lt; amount + 1; i++) {<br>            count[i] = -1;<br>        }<br>        // base cases<br>        count[0] = 0;<br>        for (int i = 0; i &lt; len; i++) {<br>            if (coins[i] &lt; amount + 1) count[coins[i]] = 1;<br>        }<br>        for (int i = 1; i &lt; amount + 1; i++) {<br>            for (int j = 0; j &lt; len; j++) {<br>                if (i - coins[j] &gt;= 0 &amp;&amp; count[i - coins[j]] != -1) {<br>                    if (count[i] == -1) {<br>                        count[i] = count[i - coins[j]] + 1;<br>                    } else {<br>                        count[i] = Math.min(count[i - coins[j]] + 1, count[i]);<br>                    }<br>                }<br>            }<br>        }<br>        return count[amount];<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6dcf16d93cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 152. Maximum Product Subarray]]></title>
            <link>https://medium.com/@hylei_73413/152-maximum-product-subarray-9c9e1c1405b1?source=rss-e04cea65fd51------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c9e1c1405b1</guid>
            <category><![CDATA[dynamic-programming]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[HAOYU LEI]]></dc:creator>
            <pubDate>Mon, 10 Sep 2018 06:35:54 GMT</pubDate>
            <atom:updated>2018-12-26T13:01:56.190Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://leetcode.com/problems/maximum-product-subarray/description/">Maximum Product Subarray - LeetCode</a></p><blockquote>Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.</blockquote><p>Solution:</p><pre>class Solution {<br>    public int maxProduct(int[] nums) {<br>        int len = nums.length;<br>        if (len == 0) return 0;<br>        int[] maximum = new int[len];<br>        int[] minimum = new int[len];<br>        maximum[0] = nums[0];<br>        minimum[0] = nums[0];<br>        for (int i = 1; i &lt; len; i++) {<br>            int maxTimesI = maximum[i-1] * nums[i];<br>            int minTimesI = minimum[i-1] * nums[i];<br>            maximum[i] = Math.max(nums[i], maxTimesI);<br>            maximum[i] = Math.max(maximum[i], minTimesI);<br>            minimum[i] = Math.min(nums[i], maxTimesI);<br>            minimum[i] = Math.min(minimum[i], minTimesI);<br>        }<br>        int globalMax = Integer.MIN_VALUE;<br>        for (int localMax: maximum) {<br>            globalMax = Math.max(globalMax, localMax);<br>        }<br>        return globalMax;<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c9e1c1405b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 206. Reverse A Linked List]]></title>
            <link>https://medium.com/@hylei_73413/classic-reverse-a-linked-list-78e834c4a872?source=rss-e04cea65fd51------2</link>
            <guid isPermaLink="false">https://medium.com/p/78e834c4a872</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[HAOYU LEI]]></dc:creator>
            <pubDate>Sun, 02 Sep 2018 07:56:34 GMT</pubDate>
            <atom:updated>2018-12-26T13:03:22.826Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://leetcode.com/problems/reverse-linked-list/description/">LeetCode - The World&#39;s Leading Online Programming Learning Platform</a></p><p>It is such a standard and classic problem that ignoring it would be too impolitic. I have a deep impression about it being the last question in final exam and I didn’t finish because I was running out of time. So it’s also worthy of a review.</p><p>The key here is to put everything aside first and identify it’s key operation: changing each node’s next pointer to point to it’s previous node, and then move to the next node. Let’s put down the pseudocode of the key operation first:</p><pre>ALGORITHM reverseList(head)<br>    current.next = previous<br>    current = current.next</pre><p>But immediately we notice certain information is missing during the operation: current.next has already changed before we move on. Therefore, we need to allocate some space to keep the original current.next:</p><pre>ALGORITHM reverseList(head)<br>    next = current.next<br>    current.next = previous<br>    current = next</pre><p>Where is previous? It is the previous node of current node in the given linked list. Where can we set it in the code? Right before we move current pointer to the next node:</p><pre>ALGORITHM reverseList(head)<br>    next = current.next<br>    current.next = previous<br>    previous = current<br>    current = next</pre><p>Ok, so this consists of the core body of our iterative solution. The rest are just conditions to terminate:</p><pre>ALGORITHM reverseList(head)<br>    current = head<br>    while current != null do<br>        next = current.next<br>        current.next = previous<br>        previous = current<br>        current = next<br>    return previous</pre><p>We should also initialize previous to null, since the original head will become tail of the new linked list:</p><pre>ALGORITHM reverseList(head)<br>    current = head<br>    previous = null<br>    while current != null do<br>        next = current.next<br>        current.next = previous<br>        previous = current<br>        current = next<br>    return previous</pre><p>Bravo!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78e834c4a872" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 53. Maximum Subarray]]></title>
            <link>https://medium.com/@hylei_73413/maximum-subarray-cd5d45b5fe4c?source=rss-e04cea65fd51------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd5d45b5fe4c</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[dynamic-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[HAOYU LEI]]></dc:creator>
            <pubDate>Sat, 18 Aug 2018 12:29:54 GMT</pubDate>
            <atom:updated>2018-12-26T13:03:42.935Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://leetcode.com/problems/maximum-subarray/description/">Maximum Subarray - LeetCode</a></p><p>This is a classic DP problem and is really good. Basically we follow a standard approach:</p><ol><li>Define: let largest[i] be the largest sum of a contiguous subarray <em>ending</em> at position <em>i </em>of nums.</li><li>Find recurrence equation: largest[i] = nums[i] + largest[i-1] if largest[i-1] &gt; 0, and largest[i] = nums[i] otherwise, since it makes no sense to include nums[i] in previous contiguous subarray if previous sum is negative — I can simply start over from nums[i].</li><li>Implement.</li></ol><p>Pseudocode (indexing start from 1):</p><pre>ALGORITHM maxSubArray(nums)<br>    For i from 2 to len(nums) do<br>         largest[i] = largest[i-1] &gt; 0? nums[i] + largest[i-1] : nums[i]<br>    return max(nums)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd5d45b5fe4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 876. Middle of Linked List]]></title>
            <link>https://medium.com/@hylei_73413/middle-of-linked-list-8fb3931c6106?source=rss-e04cea65fd51------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fb3931c6106</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[HAOYU LEI]]></dc:creator>
            <pubDate>Sat, 04 Aug 2018 14:19:05 GMT</pubDate>
            <atom:updated>2018-12-26T13:04:06.324Z</atom:updated>
            <content:encoded><![CDATA[<p>Link:</p><p><a href="https://leetcode.com/problems/middle-of-the-linked-list/description/">LeetCode - The World&#39;s Leading Online Programming Learning Platform</a></p><h3>Description</h3><blockquote>Given a non-empty, singly linked list with head node head, return a middle node of linked list.</blockquote><blockquote>If there are two middle nodes, return the second middle node.</blockquote><blockquote>Note: The number of nodes in the given list will be between 1 and 100.</blockquote><h3>Analysis</h3><p>The problem is very simple. A straightforward way is to iterate and find the length first, and then start over to return the node which in the middle:</p><pre>public ListNode middleNode(ListNode head) {<br>    // get the length of the linked list<br>    int len = 0;<br>    ListNode current = head;<br>    while (current != null) {<br>        len++;<br>        current = current.next;<br>    }<br>    current = head;<br>    int mid = len / 2;<br>    for (int i = 0; i &lt; mid; i++) {<br>        current = current.next;<br>    }<br>    return current;<br>}</pre><p>However, there’s a “smarter” approach which requires only one iteration:</p><pre>public ListNode middleNode(ListNode head) {<br>    ListNode fast = head;<br>    ListNode slow = head;<br>    while (fast != null &amp;&amp; fast.next != null) {<br>        fast = fast.next.next;<br>        slow = slow.next;<br>    }<br>    return slow;<br>}</pre><h3>Summary</h3><p>This is an interesting problem in a sense that it can be solved only with one iteration. Similar problems can be like “return the 1/3/1/4/1/5/… element in the linked list” etc etc, and we can deal with them using exactly the same tactics.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fb3931c6106" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 746. Min Cost Climbing Stairs]]></title>
            <link>https://medium.com/@hylei_73413/min-cost-climbing-stairs-2de3af343540?source=rss-e04cea65fd51------2</link>
            <guid isPermaLink="false">https://medium.com/p/2de3af343540</guid>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[HAOYU LEI]]></dc:creator>
            <pubDate>Sun, 29 Jul 2018 08:34:32 GMT</pubDate>
            <atom:updated>2018-12-26T13:04:25.520Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://leetcode.com/problems/min-cost-climbing-stairs/description/">LeetCode - The World&#39;s Leading Online Programming Learning Platform</a></p><h3>Description</h3><blockquote>On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).</blockquote><blockquote>Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1.</blockquote><h3>Analysis</h3><p>Pretty simple DP problem. Just want to do a quick recap on the process of reasoning.</p><ol><li>Define: let totalCost[i] be the cost needed to get to <em>floor</em> (remember: not step) <em>i</em>.</li><li>Find recurrence equation: how can we get totalCost[i]? Note that totalCost[i] = min(totalCost[i-1] + cost[i-1], totalCost[i-2] + cost[i-2])</li><li>What are the base cases? totalCost[0] = 0, totalCost[1] = 0.</li><li>Problem specific: remember to differentiate b/w step and floor (# of floors = cost.length + 1)</li></ol><h3>Solution</h3><h4>Initial solution</h4><pre>public int minCostClimbingStairs(int[] cost) {<br>    int len = cost.length;<br>    int[] totalCost = new int[len+1];<br>    // base cases<br>    totalCost[0] = 0;<br>    totalCost[1] = 0;<br>        <br>    for (int i = 2; i &lt; len + 1; i++) {<br>        totalCost[i] = totalCost[i-1] + cost[i-1] &lt; totalCost[i-2] + cost[i-2]? totalCost[i-1] + cost[i-1]: totalCost[i-2] + cost[i-2];<br>    }<br>    return totalCost[len];<br>}</pre><p>Time complexity: O(n) Space complexity: O(n)</p><h4>Memory improvement</h4><pre>public int minCostClimbingStairs(int[] cost) {<br>    int len = cost.length;<br>    for (int i = 2; i &lt; len; i++) {<br>        cost[i] += Math.min(cost[i-1], cost[i-2]);<br>    }<br>    return Math.min(cost[len-1], cost[len-2]);<br>}</pre><p>Time complexity: O(n) Space complexity: O(1)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2de3af343540" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>