2014.2.8 21:37
Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container.
Solution:
A very plain solution is to do a O(n^2) scan, check out every pair of (a[i], a[j]) and find out the maximal min(a[i], a[j]) * (i - j).
You know this is far from satisfactory, so let's try to find an O(n) solution.
Suppose we've got a candidate pair (a[x], a[y]), the result is min(a[x], a[y]) * (x - y). If it is currently the optimal candidate, there cannot be any a[k] >= a[x] left of a[x], or any a[k] >= a[y] right of a[y], think about why.
If we are to find a better solution (a[x'], a[y']), it must lie within the interval (x, y), and satify the condition (a[x'] > a[x] && a[y'] >= a[y]) or (a[x'] >= a[x] && a[y'] > a[y]).
This means we can scan the array from both ends in one pass, and end the algorithm when both iteraotors meet in the middle.
Time complexity is O(n), space complexity is O(1).
Accepted code:
1 // 1CE, 1AC, good. 2 #include <algorithm> 3 using namespace std; 4 5 class Solution { 6 public: 7 int maxArea(vector<int> &height) { 8 if (height.empty()) { 9 return 0; 10 } 11 12 int ll, rr, kk, result; 13 14 ll = 0; 15 rr = (int)height.size() - 1; 16 result = 0; 17 while (ll < rr) { 18 result = max(result, min(height[ll], height[rr]) * (rr - ll)); 19 if (height[ll] < height[rr]) { 20 kk = ll + 1; 21 while (kk < rr && height[kk] <= height[ll]) { 22 ++kk; 23 } 24 ll = kk; 25 } else { 26 kk = rr - 1; 27 while (kk > ll && height[kk] <= height[rr]) { 28 --kk; 29 } 30 rr = kk; 31 } 32 } 33 34 return result; 35 } 36 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)