Skip to content

11.container with most water

Problem Statement:
  • You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).
  • Find two lines that together with the x-axis form a container, such that the container contains the most water.
  • Return the maximum amount of water a container can store.
  • Notice that you may not slant the container.
Approach:
  • two pointers, left an right
    • we increment/decrement left/right respectively based on which tower is smaller and we calculate the maxCapacity at every level.
Code
class Solution {
public:
    int maxArea(vector<int>& height) {
        int i = 0;
        int j = height.size()-1;
        int maxWater = INT_MIN;
        while(i < j){
            maxWater = max(maxWater, min(height[i], height[j]) * (j - i));
            if(height[i] > height[j])
                j--;
            else
                i++;
        }
        return maxWater;
    }
};