Showcase Baseball Tournaments,
Articles V
if (height[left] < height[right]) }. Find two lines, which together with x-axis forms a container, such that the container contains the most water.The program should return an integer which corresponds to the maximum area of water that can be contained (maximum area instead of maximum volume sounds weird but this is the 2D plane we are working with for simplicity). Suppose we are given an array of non-negative integers a1, a2, a3, a4, an, where each point represents a coordinate (i, ai). ' n ' vertical lines are drawn such that the two endpoints of line i is at and . $ docker run ubuntu sleep 1000000 &. public int maxArea(int[] height) { 1752. If leftHeight < rightHeight, move right and find a value that is greater than leftHeight. Most upvoted and relevant comments will be first. Your email address will not be published. I love to learn and share. Given n non-negative integers a1, a2, , an , where each represents a point at coordinate (i, ai). If you would like to change your settings or withdraw consent at any time, the link to do so is in our privacy policy accessible from our home page.. I can not understand how this solution solve the situation when, the width between two lines can be short but if the two lines are the higest,the Area will be grather than a continer with a larger width but with shorter lenght Once unpublished, this post will become invisible to the public and only accessible to Harsh Rajpal. Since we are starting with the container of maximum width which is represented by the indices of the array, we will have to maintain two pointers who will keep track of width of the container. Excellent article. Container With Most Water. n vertical lines are drawn such that the two endpoints of line i is atand. * . . . Very well written. Return the maximum amount of water a container can store. //heights: int[] array. Find two lines, which together with x-axis forms a container, such that the container contains the most water. Am I betraying my professors if I leave a research group because of change of interest? You can add following code inside the outer while loop , Are you sure you want to hide this comment? Container With Most Water - LeetCode Got it Java || 2ms || Simple Solution arunarunarun7354 113 485 Feb 20, 2023 Java Code Container With Most Water - You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines, which together with x-axis forms a container, such that it contains the most water. If. Example 2: Input: height = [1,1] Output: 1 Constraints: n == height.length 2 <= n <= 105 0 <= height [i] <= 104 Container With Most Water - AfterAcademy n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). Site design / logo 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA. int right = height.length - 1; n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). You can find the complete source code on my GitHub repository. var sorted = objects.sort(function(a,b){ Find two lines, which, together with the x-axis forms a container, such that the container contains the most water. Container With Most Water Problem Statement Given n non-negative integers a 1, a 2, , a n , where each represents a point at coordinate (i, a i ). We are not using any data structure for intermediate results, therefore, the space complexity will be O(1). Can a judge or prosecutor be compelled to testify in a criminal trial in which they officiated? How to draw vertical line in Swing Ask Question Asked 9 years, 5 months ago Modified 3 years, 10 months ago Viewed 16k times 0 I am able to draw a horizontal line but unable to draw a vertical line. Lets take another example.Array : [3, 1, 2, 4, 5, 1]Output : 12 unitsMaximum water can be held between (3,5) vertical lines.Output= 12 =min(3,5)*( distance between both Vertical lines (4)). Everytime, we are moving our pointer i ahead if height of line at ith index is smaller or j pointer if height of line at jth index is smaller. 11 LeetCode Java: Container With Most Water - Medium Find two lines that together with the x-axis form a container, such that the container contains the most water. You must identify which two lines from the input, when together, create the container with the most water. By using our site, you n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Today we are going to discuss problem number 11 on LeetCode. width=6 Example: Given [1,3,2], the max area of the container is 2. Its the same as largest histogram problem [http://www.programcreek.com/2014/05/leetcode-largest-rectangle-in-histogram-java/ ] with the same O(N) solution. Are you sure you want to hide this comment? Example: Input: [1,8,6,2,5,4,8,3,7] Output: 49 . 2), Solution: Remove Palindromic Subsequences, Solution: Check If a String Contains All Binary Codes of Size K, Solution: Swapping Nodes in a Linked List, Solution: Best Time to Buy and Sell Stock with Transaction Fee, Solution: Generate Random Point in a Circle, Solution: Reconstruct Original Digits from English, Solution: Flip Binary Tree To Match Preorder Traversal, Solution: Minimum Operations to Make Array Equal, Solution: Determine if String Halves Are Alike, Solution: Letter Combinations of a Phone Number, Solution: Longest Increasing Path in a Matrix, Solution: Remove All Adjacent Duplicates in String II, Solution: Number of Submatrices That Sum to Target, Solution: Remove Nth Node From End of List, Solution: Critical Connections in a Network, Solution: Furthest Building You Can Reach, Solution: Find First and Last Position of Element in Sorted Array, Solution: Convert Sorted List to Binary Search Tree, Solution: Delete Operation for Two Strings, Solution: Construct Target Array With Multiple Sums, Solution: Maximum Points You Can Obtain from Cards, Solution: Flatten Binary Tree to Linked List, Solution: Minimum Moves to Equal Array Elements II, Solution: Binary Tree Level Order Traversal, Solution: Evaluate Reverse Polish Notation, Solution: Partitioning Into Minimum Number Of Deci-Binary Numbers, Solution: Maximum Product of Word Lengths, Solution: Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts, Solution: Construct Binary Tree from Preorder and Inorder Traversal, Solution: Minimum Number of Refueling Stops, Solution: Number of Subarrays with Bounded Maximum. We have to maximize the Area that can be formed between the vertical lines using the shorter line as length. [1] 47048. The naive approach is pretty intuitive. Consider these two bars and horizontal surface as the walls of the container. Container With Most Water November 26, 2021 Table Of Contents show Problem Statement Given n non-negative integers a1, a2, , an, where each represents a point at coordinate (i, ai). And thats it, We will return the maximum area at the end. max = Math.max(max, (right - left) * Math.min(height[left], height[right])); Container With Most Water - InterviewBit Find two lines that together with the x-axis form a container, such that the container contains the most water. If we want to get the maximum Area, why we should use the shorter line as length? LeetCode 11. Container With Most Water | GoodTecher Connect and share knowledge within a single location that is structured and easy to search. An example of data being processed may be a unique identifier stored in a cookie. Find two lines that together with the x-axis form a container, such that the container contains the most water. LeetCode #11 - Container With Most Water | Red Quark It will become hidden in your post, but will still be visible via the comment's permalink. In case someone is looking for video solution for this problem you can watch this: Above video and this article made understand this problem so easily! Notice that you may not slant the container. To view the purposes they believe they have legitimate interest for, or to object to this data processing use the vendor list link below. Feel free to share your thoughts on this. I feel container will be divided based on the intermediate height of pillars. Looks like this problems simplifies assumptions, not sure if its right, lo Container With Most Water Leetcode Solution, 11. . Notice that you may not slant the container. Calculate the area between the two bars and compare it with the current maximum. Output: 1, Time Complexity: My solution: There are vertical lines drawn such that the two endpoints of the (i, 0)(i, height [i]) Find two lines that together with the x-axis form a container, such that the container contains the most water. According to the problem we need to find the two lines which form a container and can store the maximum amount of water in both the vertical lines.In the above figure we can store the maximum amount of water between vertical lines present at two (with length eight) and nine (with length seven). Each represents a point at coordinate (i, ai). Now, you may ask, ok, you have moved the pointer i to 5 but can it not happen that 5 could pair up with other lines after 10 as we have neglected those lines by moving j pointer to 10. Nice explanation. Notice that you may not slant the container. if (height == null || height.length < 2) { Notice that if the first condition is valid, the variable l is increased before evaluating the second condition, which means your comparing different array items in both conditions. Data Structure & Algorithm Classes (Live), Data Structure & Algorithm-Self Paced(C++/JAVA), Full Stack Development with React & Node JS(Live), Top 100 DSA Interview Questions Topic-wise, Top 20 Interview Questions on Greedy Algorithms, Top 20 Interview Questions on Dynamic Programming, Top 50 Problems on Dynamic Programming (DP), Commonly Asked Data Structure Interview Questions, Top 20 Puzzles Commonly Asked During SDE Interviews, Top 10 System Design Interview Questions and Answers, Indian Economic Development Complete Guide, Business Studies - Paper 2019 Code (66-2-1), GATE CS Original Papers and Official Keys, ISRO CS Original Papers and Official Keys, ISRO CS Syllabus for Scientist/Engineer Exam, Find the non decreasing order array from given array, Egg Dropping Puzzle with 2 Eggs and K Floors, Find N number of solutions with the given inequality equations, Represent a number as sum of minimum possible pseudobinary numbers, Number of solutions for the equation x + y + z <= n, Find if a molecule can be formed from 3 atoms using their valence numbers, Find smallest perfect square number A such that N + A is also a perfect square number, Find an integer in the given range that satisfies the given conditions, Maximum Squares possible parallel to both axes from N distinct points, Swapping four variables without temporary variable, Check if a number can be represented as the sum of numbers with at least one digit equal to K, Count the numbers which can convert N to 1 using given operation, Sum of all N-digit palindromic numbers which doesnt contains 0 and are divisible by 9, Find maximum unreachable height using two ladders, Find remainder of array multiplication divided by n, Create a nested loop, the outer loop traverses the array from 0 to end (index of this loop is, Find the water that can be contained in the container with height of boundaries as array[i] and array[j], i.e. Once unsuspended, seanpgallivan will be able to comment and publish posts again. Given n non-negative integers a1, a2, , an, where each represents a point at coordinate (i, ai). Find two lines, which together with x-axis forms a container, such that the container contains the most water. code of conduct because it is harassing, offensive or spammy. If so, return 0 since there are not enough bars to form an area. Etc. Find two lines that together with the x-axis form a container, such that the container contains the most water. 2 Approaches: Brute Force and Two Pointers with Image - LeetCode n vertical lines are drawn such that the two endpoints of line i is at ( i , ai) and ( i, 0). such that the container contains the most water. GitHub: Let's build from here GitHub Find two lines, which together with x-axis forms a container, such that the container contains the most water. Given n non-negative integerswhere each represents a point at coordinate. So, Area = minimum {4,3}*1 = 3*1 which is equal to 3 (calculated using the above area formula). Now, it's the line on the left end that's the limiting factor, so the next step will be to slide i to the right. n vertical lines are drawn such that the two endpoints of line i is at (i, a i) and (i, 0). Examples Example 1: Given n non-negative integers a1, a2, , an , where each represents a point at coordinate (i, ai). This will take two nested loops and the time complexity will be O(n2). We only moved over one line, but we more than doubled the height. Lets see first example to understand it better . Yes, we can . Find two lines, which together with x-axis forms a container, such that the container contains the most water. Most upvoted and relevant comments will be first. I ask this because there is the possibility to have, height of a1=5 else Container With Most Water - LeetCode Note: You may not slant the container. Note : In Case of single verticle line it will not be able to hold water. Output: 49 Putting together everything, it's clear that we need to make a 2-pointer sliding window solution. Once unpublished, this post will become invisible to the public and only accessible to seanpgallivan. Notice that you may not slant the container. The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). In order to use an efficient solution to find the maximum water we can store in a container, we will start with two vertical lines, first and last, and check how much water can be stored. You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Space Complexity: [Solved] You are given an integer array height of length n. There are n Not the answer you're looking for? Once suspended, harshrajpal will not be able to comment or publish posts until their suspension is removed. var objects = []; I don't know why and what's the difference between them. Given n non-negative integers a1, a2, ., an, where each represents a point at coordinate (i, ai). That means that we always have to check at each new possible stop to see if the new container area is better than the current best. var obj = {i:i,height:heights[i]}; Share your suggestions to enhance the article. Link: https://leetcode.com/problems/container-with-most-water/. 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. 11. Container With Most Water - DEV Community Container With Most Water problem of Leetcode. rev2023.7.27.43548. So, to be noticed that if 5 would have been in the answer then any line after 10 must be >= 5 and if there is any line after 10 whose height is greater than or equal to 5 then its contribution would surely have been calculated while pointer i was at 8. while (left < right) { In this post, we are going to solve the 11. Templates let you quickly answer FAQs or store snippets for re-use. I found the below article simple and easy to understand though. Example 1: Let us discuss for new approaches. What is the most efficient approach to solving this problem?The two-pointer method is the most efficient way to solve this problem. DeclaremaxCap=0 //to store max capacitya,b //to store both vertical linesStep 1: Outer loop will run i from 0 to n(last index)Step 2: The inner loop will run j from i+1 to n(last index)Step 3: Find capacity= min(i,j)*(distance between both vertical lines).Check if the calculated capacity is more than maxCap;if yes, then update maxCap and update a,b.Step 4: Return maxCap. 'n' vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). What is happening here when the else statement is not used? What Is Behind The Puzzling Timing of the U.S. House Vacancy Election In Utah? If the value of the vertical line at which the first is pointing is lesser than the value of the second, then increment the first or decrement the second. The original question is: You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height [i]). So, not considering it makes sense. Unflagging harshrajpal will restore default visibility to their posts. Solution 1: Brute Force. Program to check if water tank overflows when n solid balls are dipped in the water tank, Check if N can be obtained from 0 using at most X increment and at most Y doubling operations, Minimum possible value T such that at most D Partitions of the Array having at most sum T is possible, Maximize element at index K in an array with at most sum M and difference between adjacent elements at most 1, Program to find amount of water in a given glass, Measure one litre using two vessels and infinite water supply, Measuring 6L water from 4L and 9L buckets, Mathematical and Geometric Algorithms - Data Structure and Algorithm Tutorials, Learn Data Structures with Javascript | DSA Tutorial, Introduction to Max-Heap Data Structure and Algorithm Tutorials, Introduction to Set Data Structure and Algorithm Tutorials, Introduction to Map Data Structure and Algorithm Tutorials, A-143, 9th Floor, Sovereign Corporate Tower, Sector-136, Noida, Uttar Pradesh - 201305, We use cookies to ensure you have the best browsing experience on our website. 2), Solution: Minimum Remove to Make Valid Parentheses, Solution: Find the Most Competitive Subsequence, Solution: Longest Word in Dictionary through Deleting, Solution: Shortest Unsorted Continuous Subarray, Solution: Intersection of Two Linked Lists, Solution: Average of Levels in Binary Tree, Solution: Short Encoding of Words (ver. Solution: Container With Most Water - DEV Community n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). 'n' vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). LeetCode Container With Most Water - DEV Community In this case, the max area of water (blue section) the container can contain is 49. OverflowAI: Where Community & AI Come Together, Leetcode #11 Container With Most Water: Why have to use 'else', Behind the scenes with the folks building OverflowAI (Ep. Find two lines that together with the x-axis form a container, such that the container contains the most water. O(n) https://leetcode.com/problems/container-with-most-water/, At each iteration, calculate the area of water trapped between the vertical lines represented by, Move the pointers inward based on the height of the lines. Therefore, the steps will be something like this . Given n non-negative integers a1, a2, ., an , where each represents a point at coordinate (i, ai). Contribute your expertise and make a difference in the GeeksforGeeks portal. n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). } To subscribe to this RSS feed, copy and paste this URL into your RSS reader. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height [i]). Container With Most Water. Question: | by Udbhav - Towards Dev Once suspended, seanpgallivan will not be able to comment or publish posts until their suspension is removed. Find two lines that together with the x-axis form a container, such that the container contains the most water. Your program should return an integer that corresponds to the maximum area of water that can be contained ( Yes, we know maximum area instead of maximum volume sounds weird.But this is a 2D plane we are working with for simplicity ). Leetcode Problem: Container With Most Water. height of a7=1 Why is {ni} used instead of {wo} in ~{ni}[]{ataru}? n vertical lines are drawn such that the two endpoints of the line i is at (i, a i) and (i, 0). Container With Most Water Solution in Java, 11. Find two lines that together with the x-axis form a container, such that the container contains the most water. N vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i,0). Find two lines, which, together with the x-axis forms a container, such that the container contains the most water. Leetcode #11. Container With Most Water - Medium here, if 8 has to be in the answer then other line that we choose should be 10 as it is the first line from the end that is at maximum distance apart from 8 and longer than 8. Therefore, in some cases both conditions are true. Similarily, if leftHeight > rightHeight, move left and find a value that is greater than rightHeight. Given n non-negative integers a1, a2, , an, where each represents a point at coordinate (i, ai). Thanks for contributing an answer to Stack Overflow! There are n vertical lines drawn such that the two endpoints of the i th line are (i, 0) and (i, height[i]). 2), Solution: The K Weakest Rows in a Matrix (ver. heights (4,3). Sharing my experience and tips as I go along. Continue with Recommended Cookies. Java Solution for Container With Most Water Problem - LeetCode Find two lines that together with the x-axis form a container, such that the container contains the most water. Java Solution - Container With Most Water - LeetCode Thanks for keeping DEV Community safe. Given n non-negative integers a1, a2, ., an. Why do we allow discontinuous conduction mode (DCM)? Discuss this article in the forums For the first example, with 1, 5, 4, 3, some of your other options are: Taking 5 and 3 together (which are 2 apart; index 1 and index 3) is the desired result, because it results in the highest area (3 * 2 = 6). return 0; Running Java in a Container | D2iQ PepCoding | Container With Most Water Find Container with Most Water. Declarationfirst =0, second = arr.length-1, maxCapacity=0Step 1: Loop until first is lesser than secondStep 2: Find the maxCapacity=min(first, second)*(distance between both vertical lines and update maxCapacity.Step 3 : If first is lesser than second then first++ else secondStep 4: If first <= second go to step one or else exit and print maxCapacity. where. 1), Solution: The K Weakest Rows in a Matrix (ver. 4. Container With Most Water Solution in C++, 11. DEV Community 2016 - 2023. So now our first and second index is pointing to the first and last vertical lines respectively. https://leetcode.com/problems/container-with-most-water/. Run a loop until first is less than the last. They can still re-publish the post if they are not suspended. In 4 simple steps you can find your personalised career roadmap in Software development for FREE, Best Courses for Data Structures & Algorithms- Free & Paid, Best Machine Learning Courses Free & Paid, Best Full Stack Developer Courses Free & Paid, Best Web Development Courses Free & Paid. You will be notified via email once the article is available for improvement. Given n non-negative integers a1, a2, ., an , where each represents a point at coordinate (i, ai). Additionally, keep tracking the max value. class Solution { public int maxArea(int[] nums) { int max = Integer.MIN_VALUE; int n = nums.length; int i = 0; int j = n - 1; while(i < j) { // The aim is to maximize the area formed between the vertical lines. Can we do better ? Output: 40 NOT single if then else statement, what is the difference between these java codes with if-else ?