DSA Problems/πŸ‘†Two Pointers

Container With Most Water

ArrayTwo PointersGreedy

Problem Statement

Given n non-negative integers where each represents a point at coordinate (i, height[i]). Find two lines that together with the x-axis form a container that holds the most water.

Approach

Use two pointers from both ends. Move the pointer pointing to the shorter line inward, as it limits the height.

Complexity Analysis

MetricValue
TimeO(n)
SpaceO(1)

Examples

Example 1

Input: height = [1,8,6,2,5,4,8,3,7] Output: 49 Explanation: Lines at index 1 and 8

Example 2

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

Constraints

  • β–Έn == height.length
  • β–Έ2 <= n <= 10^5
  • β–Έ0 <= height[i] <= 10^4
Loading...
Sign in to run your code...

Asked by companies:

AmazonFacebookGoogleMicrosoft