Pages

Wednesday, August 20, 2025

Container with Most Water (2-pointer approach)

 import java.util.*;



public class Main

{

    

    // 2pointer approach

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

        int maxWater = 0;

        int lp = 0;

        int rp = height.size()-1;

        

        while(lp < rp) {

            // calculate water

            int ht = Math.min(height.get(lp), height.get(rp));

            int width = rp- lp;

            int currWater = ht*width;

            maxWater = Math.max(maxWater, currWater);

            

            // update 2pointer

            if(height.get(lp) < height.get(rp)) {

                lp++;

            } else {

                rp--;

            }

        }

        

      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

3Sum - Leetcode solution - How i turned into two-pointer approach?

  class Solution {     public List < List < Integer >> threeSum ( int [] nums ) {         Arrays . sort (nums); // first sort...