Pages

Wednesday, August 20, 2025

Container with Most Water (Brute Force method) in Java

 import java.util.*;



public class Main

{

    

    

    public static int storeWater(ArrayList<Integer> height) {

        int maxWater = 0;

        // brute force - O(n^2)

        for(int i=0; i<height.size(); i++) {

            for(int j=i+1; j<height.size(); j++) {

                int ht = Math.min(height.get(i), height.get(j)); // L1 and L2

                int width = j-1;

                int currWater = ht * width;

                maxWater = Math.max(maxWater, currWater);

            }

        }

        

        

        return maxWater;

        

    }

public static void main(String[] args) {

ArrayList<Integer> height = new ArrayList<>();

// 1, 8, 6, 2, 5, 4, 8, 3, 7

height.add(1);

height.add(8);

height.add(6);

height.add(2);

height.add(5);

height.add(4);

height.add(8);

height.add(3);

height.add(7);

System.out.println(storeWater(height));

}

}

No comments:

Post a Comment

remove duplicates from sorted array - two pointer approach (leetcode)

  class Solution {     public int removeDuplicates ( int [] nums ) {         // base case: return if array have no el.         if ( nums...