Posted onEdited onInLeetCodeDisqus: Symbols count in article: 684Reading time ≈1 mins.
two pointers O(n) 这道题和maximum square不一样 思路和trapping most water类似,都是维护左右两个指针从外往里找短板,当前最大面积更新后,短板必须要更新成更长的板
1 2 3 4 5 6 7 8 9 10 11
classSolution: defmaxArea(self, height: List[int]) -> int: l, r, res = 0, len(height) - 1, 0 while l < r: mn = min(height[l], height[r]) res = max(res, mn * (r - l)) while l < r and height[l] <= mn: l += 1 while l < r and height[r] <= mn: r -= 1 return res
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { public: intmaxArea(vector<int>& height){ int n = height.size(); int res = 0; int l = 0, r = n - 1; while (l < r) { int mn = min(height[l], height[r]); res = max(res, mn * (r - l)); while (l < r && height[l] <= mn) { ++l; } while (l < r && height[r] <= mn) { --r; } } return res; } };