O(n^2) is a naive solution. As rule of thumb, there must be O(n) soluion. Yes - Greedy.
We assume widest container contains the most water, greedily, but it is possible that we have higher heights with narrower range, so we proceed. Of course we disgard lower heights when shrinking window - we are greedy.
class Solution { public: int maxArea(vector<int> &height) { size_t cnt = height.size(); int i = 0, j = cnt - 1; int maxWater = std::numeric_limits<int>::min(); while (i < j) { int minH = std::min(height[i], height[j]); maxWater = std::max(maxWater, minH * (j - i)); if (height[i] <= height[j]) while (height[++i] < minH && i < j); else while (height[j--] < minH && i < j); } return maxWater; } };
As shown above, I did another small optimization: when window gets shrinked, we can skip all even-shorter heights.
LeetCode "Container With Most Water" - GREEDY?
时间: 2024-10-05 13:35:49