题目连接:Leetcode 011 Container With Most Water
解题思路:计算每个位置为短板时,能储存的最大水量。
首先从左向右遍历,假设长板在短板的左边,维护一个递增的数列,并记录每块板的位置。对于每个板,在数列中找到第一个不比自己短的板的位置(二分,因为数列有序),计算储存水量,维护最大值。
同理,从右往左遍历,假设的是长板在短板的右边。
class Solution { public: int maxArea(vector<int>& height) { int ans = 0, n = height.size(); vector<int> sta; vector<int> pos; sta.push_back(height[0]); pos.push_back(0); for (int i = 1; i < n; i++) { int t = lower_bound(sta.begin(), sta.end(), height[i]) - sta.begin(); if (t < sta.size()) { ans = max(ans, height[i] * (i - pos[t])); } if (sta[sta.size()-1] < height[i]) { sta.push_back(height[i]); pos.push_back(i); } } sta.clear(), pos.clear(); sta.push_back(height[n-1]); pos.push_back(n-1); for (int i = n-1; i >= 0; i--) { int t = lower_bound(sta.begin(), sta.end(), height[i]) - sta.begin(); if (t < sta.size()) { ans = max(ans, height[i] * (pos[t] - i)); } if (sta[sta.size()-1] < height[i]) { sta.push_back(height[i]); pos.push_back(i); } } return ans; } };