Post

#11. Container With Most Water

#11. Container With Most Water
  • Solved

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:
example

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

My Solution


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Solution {
    public int MaxArea(int[] height) {
        int max = 0;

        for(int i = 0; i < height.Length - 1; i++) {
            for (int j = i + 1; j < height.Length; j++) {
                int width = j - i;
                int length = Math.Min(height[i], height[j]);

                max = Math.Max(width * length, max);
            }
        }

        return max;
    }
}

Runtime

Time Limit Exceeded

Memory

Time Limit Exceeded

Big O Notation

Time complexity: O(n^2)
Space complexity: O(1)

Best Solution


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Solution {
    public int MaxArea(int[] height) {
        int max = 0;
        int left = 0;
        int right = height.Length - 1;

        while(left < right) {
            max = Math.Max((right - left) * Math.Min(height[left], height[right]), max);

            if(height[left] > height[right]) {
                right--;
            }
            else {
                left++;
            }
        }

        return max;
    }
}

Runtime

1 ms / Beats 98.94%

Memory

61.87 MB / Beats 75.86%

Big O Notation

Time complexity: O(n)
Space complexity: O(1)

This post is licensed under CC BY 4.0 by the author.