1: class Solution {
2: public:
3: int maxArea(vector<int>& height) {
4: if (height.size() == 0) return 0;
5: int l = 0, r = height.size()-1, area = INT_MIN;
6: while (l < r) {
7: if (height[l] < height[r]) {
8: area = max(area, height[l] * (r-l));
9: l++;
10: } else {
11: area = max(area, height[r] * (r-l));
12: r--;
13: }
14: }
15: return area;
16: }
17: };
Monday, August 15, 2016
11. Container With Most Water
The idea is to compute the container from the widest to highest. Starting from two ends, we get the widest container's area. Then question is how we can get a container that has larger area? Since we are going to shrink the container's width, the only chance we can get a larger area is to have taller container such that height offsets the width. So we move the shorter end toward to the taller end with hoping to find a even taller end.
Labels:
array,
leetcode,
two pointers
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment