<?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 Zhuozhuo Liu on Medium]]></title>
        <description><![CDATA[Stories by Zhuozhuo Liu on Medium]]></description>
        <link>https://medium.com/@joylovemercy?source=rss-1a3ec66f3378------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Y0pRTCUoQEnUHDoOGY1yog.jpeg</url>
            <title>Stories by Zhuozhuo Liu on Medium</title>
            <link>https://medium.com/@joylovemercy?source=rss-1a3ec66f3378------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 17:32:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@joylovemercy/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[Leetcode # 134. Gas Station || Step-by-step Explanation(with graph) || Beginners Friendly]]></title>
            <link>https://medium.com/@joylovemercy/leetcode-134-gas-station-step-by-step-explanation-with-graph-beginners-friendly-1a4ff73abfb0?source=rss-1a3ec66f3378------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a4ff73abfb0</guid>
            <category><![CDATA[leetcode-medium]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <dc:creator><![CDATA[Zhuozhuo Liu]]></dc:creator>
            <pubDate>Sat, 22 Aug 2020 16:07:47 GMT</pubDate>
            <atom:updated>2020-08-24T16:24:41.293Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leetcode <strong>#134. Gas Station || Step-by-step Explanation(with graph) || Beginners Friendly</strong></h3><h3>Problem</h3><p>There are N gas stations along a circular route, where the amount of gas at station i is gas[i].</p><p>You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.</p><p>Return the starting gas station’s index if you can travel around the circuit once in the clockwise direction, otherwise return -1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*6JcViZQrkWQY71g8PqqESQ.png" /></figure><p><strong>Note</strong></p><p>If there exists a solution, it is guaranteed to be unique.</p><p>Both input arrays are non-empty and have the same length.</p><p>Each element in the input arrays is a non-negative integer.</p><p><strong>Author’s note</strong></p><p>This question may use greedy algorithm which involves mathematical proofs.</p><h3><strong>Idea 1: Brute Force</strong></h3><p>We will have to start from every station and check if we have enough gas to go to the next station with `remainGas = remainGas + gas[station] — cost[station]`. If not `remainGas &lt; 0`, we break and move the starting point to the next station and keep checking until we find a starting point that sustains us to travel around.</p><h4><strong>Time cost</strong></h4><p>O(n). Because we have two pointers (both traverse O(n) times) and one is nested in the other one.</p><h4><strong>Code</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a4d8ebc9d27c4c0ebac4e2dca7d5a6c/href">https://medium.com/media/4a4d8ebc9d27c4c0ebac4e2dca7d5a6c/href</a></iframe><h3><strong>Idea 2: One pass</strong></h3><p>After coming up with brute force, you always ask yourself, are all procedures or calculations necessary? The answer is NO. The solution depends on 3 properties. Every property saves us a bunch of work compared to brute force.</p><h4><strong>Code</strong></h4><p>Let’s reveal the algorithm first and then analyze properties and how they help with simplifying the procedure.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22d3d161bd2adcf7136aedf0315f8206/href">https://medium.com/media/22d3d161bd2adcf7136aedf0315f8206/href</a></iframe><h4><strong>Property 1. If total gas &lt; total cost, a successful route doesn’t exist.</strong></h4><p>This is obvious.</p><p>Question: How to prove that if total gas &gt;= total cost, there must be a successful route?</p><p><strong>Simplify the code</strong></p><p>With this property, we can check at the very beginning (or at the end).</p><h4><strong>Property 2. If path(#i -&gt; #j) failed, it will also fail if we start with any station between #i and #j.</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*KrUdou4tcz2Ew8_zIZ9qMg.png" /></figure><p>Consider this graph as an example: if we start from #1:</p><ul><li>path(#1 -&gt; #3) is successful</li><li>path(#3 -&gt; #4) fails</li></ul><p>With the brute force idea, if #1 doesn’t work out we have to start with #2 to check. Is it necessary? No. We don’t have to check from #2 because we’ve known that it won’t pass #4.</p><p>Why?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*-ewSXEPsfV-j9HVErmZ6dw.png" /></figure><p>Why? Starting from #2 can be equal to starting from #1, adding 1 gas at #1 (originally gas = 2 at #1). That equals to, #1 doesn’t provide us any benefits.</p><p>We knew that path(#1 -&gt; #4) fails. That’s being said, even if #1 provides us some extra benefits to let us have gas remaining when arriving at #2, that gas doesn’t sustain us to pass #4.</p><p>Therefore, path(#2 -&gt; #4) wouldn’t work. We can prove in contradiction. If it works, path(#1 -&gt; #4) should work as well because #1 may provide extra gas for the trip.</p><p>With this property, we further conclude that, once we find a failed path(#i -&gt; #j), we can set up the starting point from the next point #j+1.</p><p><strong>Simplify the code</strong></p><p>With this property, we further conclude that, once we find a failed path(#i -&gt; #j), we can set up the starting point from the next point #j+1. In the code, `start = i+1`.</p><h4><strong>Property 3. With the condition total gas &gt; total cost, if there’s a successful path(#X -&gt; #last station), starting X must be valid.</strong></h4><p>That’s being said, if we find a starting point X that can reach the last station, we don’t have to loop back to check stations before X. The gas will always be enough to cover the rest trip (in this example, #5 is the last station but may not be the last one in the route because the starting point is not always #1).</p><p>It sounds unbelievable. Let’s prove. In this graph, the whole route is divided by green section path(#X -&gt; #n) and blue section path(#n -&gt; #X-1). We want to prove that if green section works, the blue section must work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*-m1imB9kt4Sc2g5UzTGD3A.png" /></figure><p><strong>Notations</strong></p><ul><li>#X = starting point</li><li>#n = last station in alphabetics order (not the last station in the route)</li><li>k = the remaining gas after going path(#X -&gt; #n) (before adding gas from #n)</li></ul><p><strong>Proof</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*EDhLm5k2qj4Zl7LqfaQhLw.jpeg" /></figure><p>This formula shows that the sum of x remaining gas at #n and the gas being added must be able to cover the cost during the blue section. Therefore, as long as the green section works, the blue section must work.</p><p><strong>Simplify the code</strong></p><p>With this property, we don’t have to circle around and check the stations in front of the starting point. So the loop is `for (int i = 0; i &lt; gas.length; i++)`.</p><blockquote>Hope this explanation helps! If you like it, don’t forget to like and follow❤️.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a4ff73abfb0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[# 277. Find the Celebrity || Linear Comparison O(n) || Step-by-step Explanation(w/ graph) ||…]]></title>
            <link>https://medium.com/@joylovemercy/277-find-the-celebrity-linear-comparison-o-n-step-by-step-explanation-w-graph-8928230c6e?source=rss-1a3ec66f3378------2</link>
            <guid isPermaLink="false">https://medium.com/p/8928230c6e</guid>
            <category><![CDATA[leetcode-medium]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Zhuozhuo Liu]]></dc:creator>
            <pubDate>Wed, 19 Aug 2020 02:14:32 GMT</pubDate>
            <atom:updated>2020-08-19T05:17:05.832Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Leetcode # 277. Find the Celebrity || O(n) || Step-by-step Explanation(with graph) || Beginners friendly</strong></h3><h3><strong>Problem</strong></h3><p>Suppose you are at a party with n people (labeled from 0 to n — 1) and among them, there may exist one celebrity. The definition of a celebrity is that all the other n — 1 people know him/her but he/she does not know any of them.</p><p>Now you want to find out who the celebrity is or verify that there is not one. The only thing you are allowed to do is to ask questions like: “Hi, A. Do you know B?” to get information of whether A knows B. You need to find out the celebrity (or verify there is not one) by asking as few questions as possible (in the asymptotic sense).</p><p>You are given a helper function bool knows(a, b) which tells you whether A knows B. Implement a function int findCelebrity(n). There will be exactly one celebrity if he/she is in the party. Return the celebrity’s label if there is a celebrity in the party. If there is no celebrity, return -1.</p><h3><strong>Idea 1: Brute Force</strong></h3><p>For each number i, we need to check if i is a celebrity or not. How to check? We check all knows(i, j) where j from 0 to n. Only when all pairs of knows(i, j) == 0 &amp;&amp; all pairs of knows(j, i) ==1, we know i is a celebrity. Otherwise, i is not a celebrity.</p><p>T(n) = O(n²), since we need to check n numbers, and for each number we need to pair it with n-1 numbers to check. Another way to think about it is to check all n² pairs of knows(i, j).</p><h3><strong>Idea 2: </strong>Linear Elimination</h3><p>Do we need to check all pairs of knows(i, j)? We don’t.</p><p>If i knows j, that means i is not the celebrity because a celebrity doesn’t know anyone.</p><p>If i doesn’t know j, that means j is not the celebrity because everyone knows the celebrity.</p><p>If you understand the above, you know two secrets of knows(i, j):</p><ul><li>Secret 1. If knows(i, j) = 1, i is not the celebrity.</li><li>Secret 2. If knows(i, j) = 0, j is not the celebrity.</li></ul><p>We will, and only will, get two results: 0 or 1 after calling `knows`. So with each call to `knows(i, j)`, we can eliminate a non-celebrity from n.</p><p>Based on the above analysis, we design the algorithm below:</p><ol><li>Base case: i = 0, j = 1. We check knows(0, 1) and determine a potential candidate.</li></ol><ul><li>If knows(0, 1) = 1, j is the potential candidate.</li><li>If knows(0, 1) = 0, i is the potential candidate.</li></ul><p>2. After determining a candidate between 0 and 1, we need to compare the winning candidate with a 3rd number. Therefore, we need a for loop to always go to the next number so that the candidate can compare to.</p><p>For loop where j traverses all numbers:</p><ul><li>If knows(candidate, j) == 1 we eliminate the current candidate and set `candidate = j`.</li><li>If knows(candidate, j) == 0 we eliminate j=1 and keep the current candidate.</li></ul><p>After running up all numbers, we will get a final candidate X. Also we know that, if a celebrity exists, it must be X.</p><p>Here is a tree that demonstrates all possible paths. At each level we will add a new number to compare with, so the height/time cost is theta(n).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*sKgaFrdPPTGpPHikameaPA.png" /></figure><p>Are we done? No. This final candidate X is just our best guess! Remember to check if X is the real celebrity!</p><p>Why? Because we only compared the final candidate X once, we don’t know the relationship between X and other numbers. Since there can be no celebrity, maybe X is not. We trust X just because other numbers are definitely not!</p><p>So, we need one more step to check X:</p><p>3. Check if knows(final candidate, k) == 0 &amp;&amp; knows(k, final candidate) == 1. If true, it is the real celebrity that we are looking for.</p><h4><strong>Code</strong></h4><pre>public class Solution extends Relation {<br>    public int findCelebrity(int n) {<br>        // Compare and eliminate one that is not celebrity. Compare with the next number until reaching the last number.<br>        int candidate = 0;<br>        for (int j = 1; j &lt; n; j++)<br>            if (knows(candidate, j)) {<br>                candidate = j; // We get a final candidate by linear comparison<br>            }<br><br>        // Check if the final candidate is the celebrity<br>        for (int k = 0; k &lt; n; k++) {<br>            if (candidate == k) continue;<br>            if (knows(candidate, k) || !knows(k, candidate)) { // If it knows someone, or someone doesn&#39;t know it, it&#39;s not a celebrity<br>                return -1;<br>            }<br>        }<br>        return candidate;<br>    }<br>}</pre><blockquote>Hope this explanation helps! You can find it on <a href="https://leetcode.com/problems/find-the-celebrity/discuss/799675/O(n)-oror-Step-by-step-Explanation-(w-graph)-oror-Beginners-Friendly">Leetcode discussions board</a> as well. If it helps you, upvote please!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8928230c6e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode #80. Remove Duplicates from Sorted Array || Explanation For Beginners (with graph)]]></title>
            <link>https://medium.com/@joylovemercy/leetcode-80-remove-duplicates-from-sorted-array-explanation-for-beginners-with-graph-4b3ec43cc47a?source=rss-1a3ec66f3378------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b3ec43cc47a</guid>
            <category><![CDATA[leetcode-medium]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Zhuozhuo Liu]]></dc:creator>
            <pubDate>Fri, 14 Aug 2020 22:28:30 GMT</pubDate>
            <atom:updated>2020-08-19T02:17:46.330Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leetcode #80. Remove Duplicates from Sorted Array || Step-by-step Explanation (with graph) || Beginners Friendly</h3><h3>Problem</h3><p>Given a sorted array <em>nums</em>, remove the duplicates <a href="https://en.wikipedia.org/wiki/In-place_algorithm">in-place</a> such that duplicates appeared at most <em>twice</em> and return the new length.</p><p>Do not allocate extra space for another array, you must do this by modifying the input array <a href="https://en.wikipedia.org/wiki/In-place_algorithm">in-place</a> with O(1) extra memory.</p><h3>Author’s note</h3><p>This question is asking us to return a “new length”. However, as we know, the array’s length is immutable in Java. It’s actually asking us to REPLACE the duplicate with other “safe” numbers and return the length of the “prefix” of this array. We don’t care what the rest looks like — only make sure the “prefix” is correct.</p><h3>Prerequisites</h3><p>Before solving this question, you should have completed #27. Remove Element and #26. Remove Duplicates from Sorted Array.</p><h3>Idea: Counting the duplicate</h3><ol><li>It’s asking us to keep the 1st duplicate number and remove other duplicates if any. If the array is [0, 0, 1, 1, <em>1</em>, 2, 3, 3], we need to remove the 3rd 1 and keep the rest.</li><li>Let’s call a number “<em>safe</em>” if it’s our 1st and 2nd time to see it. We call it “<em>unsafe</em>” if we see it more than twice. We need to keep <em>safe numbers</em> and replace the <em>unsafe numbers</em>.</li><li>Therefore, we need a <em>counter k</em> to count the ordinal of duplicates:</li></ol><ul><li>k=1 means it’s the 1st time we see a certain number. It’s a 1st-time <em>safe number.</em></li><li>k=2 means it’s the 2nd time we see a certain number. It’s a 2nd-time <em>safe number</em>.</li><li>A <em>safe number</em> can either be a 1st-time <em>safe number</em> or a 2nd-time <em>safe number</em>.</li><li>k=3 means it’s the 3rd time we see a certain number. It’s the first <em>unsafe number</em> that we need to replace.</li></ul><p>4. What should be replaced with the <em>unsafe number</em>? The answer is a new <em>safe number</em>.</p><ul><li>We need a <em>pointer j </em>to traverse all numbers to find new <em>safe numbers</em>.</li><li>We also need a <em>pointer i</em> to mark the last <em>safe number</em>.</li><li><em>Pointer i</em> will wait on its position until <em>pointer i</em> found a new <em>safe number.</em></li></ul><p>5. If you don’t fully understand 1–4, it doesn’t matter. Code will tell the story by itself. Let me explain line by line.</p><pre>public int removeDuplicates(int[] nums) {<br>    //Set up pointer i to mark the last safe number. Initialize it to 0 to start from the first number.<br>    int i = 0;<br>    //Set up counter k to count the ordinal of duplicates. Initialize it to 1 to denote the &quot;kth&quot; time that we see a number.<br>    int k = 1;<br><br>    //Create a loop where j can traverse all numbers in the array, except the first number (because we use 2 pointers so the first number has been represented by i=0)<br>    for (int j = 1; j &lt; nums.length; j++) {<br>        //When nums[i] == nums[j], we have found a duplicate number. Maybe it&#39;s safe if it&#39;s a 2nd-time safe number. So we use k to count the ordinal of this duplicate.<br>        if (nums[i] == nums[j]) {<br>            k++;<br><br>            //Pointer i moves by 1 when we found a 2nd-time safe number. We assign that value to nums[i+1].<br>            if (k == 2) {<br>            i++;<br>            nums[i] = nums[j];<br>        }<br>        //We don&#39;t do anything if k&gt;=3<br>        //When nums[i] != nums [j], pointer i moves by 1 since we found a different number - a 1st-time safe number. We assign that value to nums[i+1].<br>        } else {<br>            k = 1;<br>            i++;<br>            nums[i] = nums[j];<br>        }<br>    }<br>    return i+1;<br>}</pre><h3>Iterations will go as follows</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*hDHNyBEES6jSqhqYtWXAhw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*WI0lwJcXLdYcF7kVj_StOA.jpeg" /></figure><h3>Idea 2: Comparing with <strong>nums[i-1]</strong></h3><p>Is the counter necessary? Can we not use counter? Yes!</p><p>Let’s recall what we can do without the counter. We have nums[j] who is traversing all numbers to find safe numbers. We have a “prefix” array from nums[0] to nums[i] which contains a “correct” output that i has been “guarding”. Since we don’t use counter this time, counter k is out.</p><p>How to identify if a new number nums[j] is safe or not? We can compare nums[j] with the second-to-last numbers in the “prefix” array that is nums[i-1]. If nums[j] == nums[i-1], nums[j] is not the safe number. If nums[j] != nums[i-1], nums[j] must be a safe number.</p><p>Why? Let’s assume nums[j] = nums[i-1] = 7, there’s only 1 scenario, that is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/163/1*gQQFEhnrh9CPxTNKmu4kAQ.png" /></figure><p>All numbers from nums[i-1] to nums[j] are the same! So nums[j] is at least a 3rd-time duplicate unsafe number. This is why we need to compare it with nums[i-1] instead of nums[i].</p><p>To satisfy our curiosity — what happens when nums[j] != nums[i-1]? There are 3 scenarios:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*GUu3fWZLZ_TOFwL1YzH_Ag.png" /></figure><p>nums[j] is safe in all scenarios!</p><p>Therefore, we understand why it’s a nice way to compare nums[j] with nums[i-1].</p><h3>Code</h3><pre>class Solution {<br>    public int removeDuplicates(int[] nums) {<br>        int i = 0;<br>        for (int j = 1; j &lt; nums.length; j++) {<br>            if (i &lt; 1 || nums[j] != nums[i-1]) {<br>                i++;<br>                nums[i] = nums[j];<br>            }<br>        }<br>        return i+1;<br>    }<br>}</pre><p>We can simplify it by using foreach loop since we are not interested in index j:</p><pre>class Solution {<br>    public int removeDuplicates(int[] nums) {<br>        int i = 0;<br>        for (n : nums) {<br>            if (i &lt; 1 || n != nums[i-1]) {<br>                i++;<br>                nums[i] = n;<br>            }<br>        }<br>        return i+1;<br>    }<br>}</pre><blockquote>Hope this explanation helps! You can find it on <a href="https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/discuss/792178/Java-oror-2-pointers-100-faster-oror-Step-by-step-explanation-(with-graph)-oror-Beginners-friendly">Leetcode discussions board</a> as well. If it helps you, upvote please!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b3ec43cc47a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode #11. Container With Most Water || A simple explanation to algorithm || Beginners friendly]]></title>
            <link>https://medium.com/@joylovemercy/leetcode-11-container-with-most-water-a-simple-explanation-to-algorithm-beginners-friendly-970444ba5aa2?source=rss-1a3ec66f3378------2</link>
            <guid isPermaLink="false">https://medium.com/p/970444ba5aa2</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[leetcode-medium]]></category>
            <dc:creator><![CDATA[Zhuozhuo Liu]]></dc:creator>
            <pubDate>Thu, 13 Aug 2020 22:33:33 GMT</pubDate>
            <atom:updated>2020-08-19T02:18:13.758Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leetcode #11. Container With Most Water || Step-by-step Explanation to Algorithm|| Beginners Friendly</h3><h3>Problem</h3><p>Given <em>n</em> non-negative integers <em>a1</em>, <em>a2</em>, …, <em>an </em>, where each represents a point at coordinate (<em>i</em>, <em>ai</em>). <em>n</em> vertical lines are drawn such that the two endpoints of line <em>i</em> is at (<em>i</em>, <em>ai</em>) and (<em>i</em>, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/0*TfvtfvoTfGWyEHIg.jpeg" /></figure><h3>Idea 1: Brute force</h3><ol><li>Calculate the area of all possible containers S(i, j)。Here, S(i, j)=min(i, j)*(j-i).</li><li>We need to use two pointers: i, j. When i=1，j moves from the next integer, which is 2, after i to the end, which is n. Calculate S(i, j)。Then, i moves to the next integer which is 2. j starts from i+1 to n. Repeatedly doing this until i reach n-1.</li><li>We also need a variable to record the max area among all possible S. It’s easy. We set up and initialize maxArea=-1. If we find any S&gt;max，we assign the value of S to maxArea. Otherwise, we don’t change the value of maxArea so that maxArea always stands for the max value among S.</li><li>T(n)=O(n²). One way to think about is that we have a nested loop (j nested in i). Another way to think about it is “how many possible containers that n lines can make up, if we pick 2 every time”. We use combination to answer this question: the possible combinations in picking 2 lines from n will be C(n, 2)=n*(n-1)/2=O(n²).</li></ol><h3>Idea 2: 2 pointers going inwards</h3><p>I will reveal the solution first and then analyze and prove it.</p><ol><li>We need to use two pointers i and j. i starts from the 1st integer, j starts from the last integer.</li><li>Then, we calculate the area S(1, n)。Here, S(i, j)=min(i, j)*(j-i).</li><li>(Important) What are the next two integers to form the container? We pick the shorter line between 1 and n, which is min(i, j). Let’s assume i=1 is shorter. Then we move the pointer from i=1 to the next integer of i, which is i=2. At the same time, we hold j=n in position, which is the longer one. This time, we use i=2 and j=n to from a new container.</li><li>Calculate the area of the new container.</li><li>Always move the shorter one to the next integer (move towards the center: i moves right-wards, j moves left-wards) and hold the longer one in place to form the new container.</li><li>We also need a variable to record the max area among all possible S. It’s easy. We set up and initialize maxArea=-1. If we find any S&gt;max, we assign the value of S to maxArea. Otherwise, we don’t change the value of maxArea so that maxArea always stands for the max value among S.</li></ol><h3>Explanation to the algorithm</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/0*YttA494zZH-o0Oig.png" /></figure><ol><li>This graph pictures the initialization stage: i &lt; j. From the perspective of i=1, its best choice is j=n among all integers from j=2 to j=n. Why? Because the height of the container that i make up is at most i’s length: if i=1 meets a longer one, the height will still be limited by i’s length; if i meets a shorter one, the height will be even worse. So, among all integers, i’s best strategy is to find the furthest integer, which is n.</li><li>If you understand the above, you understand 3 general properties for any pair(i, j) :</li></ol><ul><li>The shorter one doesn’t have to form containers with any other integers between i and j, since j beats all of them.</li><li>The shorter one may not be the longer one’s best choice.</li><li>The longer one still has the chance to form larger containers with lines in between i and j. So the longer one still needs to search.</li></ul><p>3. If you understand the above, you are 90% to understand the solution.</p><ul><li>In the solution, the pair(i, j) starts from (1, n). Let’s assume line i=1 is shorter. Then, we abandon i=1 and move the pointer i to the next integer in between i and j, which is i=2, since i=1 has already found its best choice but j=n hasn’t.</li><li>In the next pair (2, n), assume line j=n is shorter, we abandon j=n and move the pointer j to the next integer in between i and j, which is j=n-1, since j=n has found its best choice but i=2 hasn’t.</li><li>We repeat the above steps until two pointers meet. In this way, every integer has found its best choice.</li></ul><p>4. Why T(n)=O(n)?</p><ul><li>It’s because in pair (1, n), we eliminate n-2 unnecessary comparisons for the shorter one.</li><li>In the second iteration (2, n) or (1, n-1), we eliminate n-3 unnecessary comparisons for the shorter one.</li><li>……</li><li>In the second last iteration, we eliminate 1 unnecessary comparison for the shorter one.</li><li>In the last iteration, we eliminate 0 unnecessary comparison for the shorter one.</li><li>In sum, we eliminate m=(n-2)+(n-3)+…+2+1 unnecessary comparisons from C(n, 2)=n*(n-1)/2. The actual comparisons that we implemented are C(n, 2)-m which is n-1.</li></ul><p>5. Another way to interpret this T(n)=n-1 is that, we have implemented n-1 iterations. That means, we have calculated the area for n-1 containers.</p><p>Why? Think about an easy scenario when n is the longest line among all. Then the iterations go from (1, n) to (n-1, n) because j=n never changes its place. In this scenario, we move i from 1 to n-1 so there are n-1 iterations in total.</p><h3>Final solution</h3><p>The Java solution is very similar to Javascript for this problem. Just replace “int” with “let”. The rest are the same.</p><pre>class Solution {<br>    public int maxArea(int[] height) {<br>        //Initialize pointers and max<br>        int maxArea = -1; //JS: int =&gt; let<br>        int i = 0; //JS: int =&gt; let<br>        int j = height.length-1; //JS: int =&gt; let        //Loop for pointers<br>        while (i &lt; j) {<br>            int area = (j-i)*Math.min(height[i], height[j]); //JS: int =&gt; let<br>            maxArea = Math.max(maxArea, area);<br>            if (height[i] &lt; height[j]) {<br>                i++;<br>            } else {<br>                j--;<br>            }<br>        }<br>        return maxArea;<br>    }<br>}</pre><blockquote><em>Hope this explanation helps! You can find it on </em><a href="https://leetcode.com/problems/container-with-most-water/discuss/790047/Explain-the-algorithm-using-simple-language-oror-Prove-the-correctness-oror-For-beginners"><em>Leetcode discussions board</em></a><em> as well. If it helps you, upvote please!</em></blockquote><p>Reference: <a href="https://leimao.github.io/blog/Proof-Container-With-Most-Water-Problem/">Lei Mao’s Log Book — Simple Proof to the Container With Most Water Problem</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=970444ba5aa2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>