Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.thealgorithms.misc;

/**
* Finds the maximum amount of water a container can store given an array of
* heights. Uses a two-pointer approach starting from both ends.
*
* <p>Example: height = [1,8,6,2,5,4,8,3,7] -> 49
*
* <p>Time complexity: O(n), Space complexity: O(1)
*
* @see <a href="https://leetcode.com/problems/container-with-most-water/">LeetCode #11</a>
*/
public final class ContainerWithMostWater {
private ContainerWithMostWater() {
}

public static int maxArea(int[] height) {
int left = 0;
int right = height.length - 1;
int maxWater = 0;
while (left < right) {
int water = Math.min(height[left], height[right]) * (right - left);
maxWater = Math.max(maxWater, water);
if (height[left] < height[right]) {
left++;
} else {
right--;
}
}
return maxWater;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.thealgorithms.misc;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;

public class ContainerWithMostWaterTest {

@Test
public void testExample() {
assertEquals(49, ContainerWithMostWater.maxArea(new int[] {1, 8, 6, 2, 5, 4, 8, 3, 7}));
}

@Test
public void testTwoElements() {
assertEquals(1, ContainerWithMostWater.maxArea(new int[] {1, 1}));
}

@Test
public void testDescending() {
assertEquals(4, ContainerWithMostWater.maxArea(new int[] {4, 3, 2, 1}));
}

@Test
public void testEqualHeights() {
assertEquals(8, ContainerWithMostWater.maxArea(new int[] {2, 2, 2, 2, 2}));
}
}
Loading