Road to coding interview (Day 4)

eecheng
May 3, 2021
Photo by Austin Distel on Unsplash

Day 4, let’s move on problem 11. Container With Most Water.

class Solution {
public:
int maxArea(vector<int>& height) {
int i = 0, j = height.size() - 1;
int res = -1;

while(i < j){
int h = min(height[i], height[j]);
res = max(res, h * (j - i));
while(height[i] <= h && i < j)i++;
while(height[j] <= h && i < j)j--;
}
return res;
}
};

Summarize the solution from StefanPochmann

The tip is that using the first and the last line as base result. All other possible containers are less wide, so to hold more water, they need to be higher. Thus, after evaluating that widest container, skip lines at both ends that don’t support a higher height. Then evaluate that new container we arrived at.

--

--