Container with Most Water

1 minute read

This program was created to find two lines (similar to a bar graph) that form a container with the most water.

It returns the maximum amount of water.

The code has been modified slightly and now uploaded to the site.

<— Return Home

Solution.java

// Source: https://leetcode.com/problems/container-with-most-water/
// TIME LIMIT EXCEEDED WHEN THIS CODE IS RUN
public class Solution {
    public static void main(String[] args) {
        // int[] height = {1, 8, 6, 2, 5, 4, 8, 3, 7};
        int[] height = {4, 3, 2, 1, 4};
        // int[] height = {1, 1};
        int result = maxArea(height);
        System.out.println(result);
    }

    public static int maxArea(int[] height) {
        // int counter = 0;
        // int range = ((int)(Math.round(height.length / 2)));
        // int[] area = new int[height.length + 1];
        int area = 0;
        // ArrayList<Integer> areaArray = new ArrayList<Integer>();
        boolean check = false;
        boolean check2 = false;
        for (int i = 0; i < height.length; i++){
            // for (int j = height.length - 1; j > 0; j--){
            for (int j = i + 1; j < height.length; j++){
                check = height[i] * (j - i) > area;
                check2 = height[j] * (j - i) > area;
                if ((height[i] < height[j] || height[i] == height[j]) && check){
                    area = height[i] * (j - i);
                    // areaArray.add(area);
                }
                else if (height[j] < height[i] && check2){
                    area = height[j] * (j - i);
                    // areaArray.add(area);
                }
                // else if (height[j] == height[i] && check) {
                //     area = height[i] * (j - i);
                //     // areaArray.add(area);
                // }
            }
        }
        // int temp = area[0];
        // for (int i = 0; i < area.length; i++){
        //     if (area[i] > temp){
        //         temp = area[i];
        //     }
        // }
        // return temp;
        // System.out.println(areaArray);
        return area;
    }
}

<— Return Home