LeetCode 0011. Container With Most Water Solution Java | Python | C/C++ | JavaScripts | Go | Rust ++

CoderIndeed
0
0011. Container With Most Water

Description

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 that together with the x-axis form a container, such that the container contains the most water.

Return the maximum amount of water a container can store.

Notice that you may not slant the container.

 

Example 1:

Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example 2:

Input: height = [1,1]
Output: 1

 

Constraints:

  • n == height.length
  • 2 <= n <= 105
  • 0 <= height[i] <= 104

Solutions

Solution 1: Two Pointers

We use two pointers l and r to point to the left and right ends of the array, respectively, i.e., l = 0 and r = n - 1, where n is the length of the array.

Next, we use a variable ans to record the maximum capacity of the container, initially set to 0.

Then, we start a loop. In each iteration, we calculate the current capacity of the container, i.e., min(height[l], height[r]) × (r - l), and compare it with ans, assigning the larger value to ans. Then, we compare the values of height[l] and height[r]. If height[l] < height[r], moving the r pointer will not improve the result because the height of the container is determined by the shorter vertical line, so we move the l pointer. Otherwise, we move the r pointer.

After the iteration, we return ans.

The time complexity is O(n), where n is the length of the array height. The space complexity is O(1).

PythonJavaC++GoTypeScriptRustJavaScriptC#PHPC
class Solution: def maxArea(self, height: List[int]) -> int: l, r = 0, len(height) - 1 ans = 0 while l < r: t = min(height[l], height[r]) * (r - l) ans = max(ans, t) if height[l] < height[r]: l += 1 else: r -= 1 return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !