LeetCode 75
Container With Most Water
- Problem
- LC 11
- Topic
- Two Pointers
- File
- official75_LC11ContainerWithMostWater.java
- Path
- pkg5leetcode/official75/official75_LC11ContainerWithMostWater.java
- Package
- pkg5leetcode.official75
- Command
- java pkg5leetcode/official75/official75_LC11ContainerWithMostWater.java
- Approach
- Two pointers move shorter height inward.
- Complexity
- Time O(n), Space O(1)
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg5leetcode.official75;2 3/*4 * Container With Most Water | LC 115 * APPROACH: Two pointers move shorter height inward.6 * COMPLEXITY: Time O(n), Space O(1)7 */8public class official75_LC11ContainerWithMostWater {9 static int maxArea(int[] height) {10 int l = 0, r = height.length - 1, best = 0;11 while (l < r) {12 best = Math.max(best, Math.min(height[l], height[r]) * (r - l));13 if (height[l] < height[r]) l++; else r--;14 }15 return best;16 }17 18 public static void main(String[] args) {19 check(maxArea(new int[]{1,8,6,2,5,4,8,3,7}) == 49, "case1");20 check(maxArea(new int[]{1,1}) == 1, "case2");21 System.out.println("all tests passed");22 }23 24 static void check(boolean cond, String name) {25 if (!cond) throw new AssertionError("FAILED: " + name);26 System.out.println(" PASS " + name);27 }28}