11. Container With Most Water

Container With Most Water - LeetCode

 

Container with Most Water - GeeksforGeeks

Approach :

  • This implies that if there was a better solution possible, it will definitely have the Height greater than min(a1, aN).
     Base * Height > (N-1) * min(a_1, a_N)
  • We know that, Base min(a1, aN)
    This means that we can discard min(a1, aN) from our set and look to solve this problem again from the start.
  • If a1 < aN, then the problem reduces to solving the same thing for a2, aN.
  • Else, it reduces to solving the same thing for a1, aN-1

 

 

In the two-pointer solution for the "Container With Most Water" problem, the key idea is to maximize the area formed by the vertical lines at the left and right pointers. The area between two lines is determined by both the height of the shorter line and the distance between the two pointers. The decision to "move the pointer at the shorter line inward" helps us optimize this process.

Why move the pointer at the shorter line inward?

  • The area between two lines is calculated as:

    Area=min⁡(height[left],height[right])×(right−left)\text{Area} = \min(\text{height}[left], \text{height}[right]) \times (\text{right} - \text{left})

    The width between the two pointers decreases as the pointers move toward each other. So, to maximize the area, the height must increase to compensate for the loss in width.

  • The height of the container is determined by the shorter of the two lines (because the water can't be taller than the shorter side). If you move the pointer at the shorter line inward, you might find a taller line, which could increase the height and potentially lead to a larger area.

Key Logic:

  • If height[left] < height[right], this means the line at left is the shorter one. To find a potentially taller line and increase the area, move the left pointer inward (left++).
  • If height[left] >= height[right], the line at right is the shorter or equal. To increase the height, you move the right pointer inward (right--).

By always moving the pointer at the shorter line, you give yourself the chance to find a taller line and potentially maximize the area.

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(161)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2018-02-02 git分支演示
2015-02-02 如何实现wpf的多国语言
点击右上角即可分享
微信分享提示