LeetCode Entry

11. Container With Most Water

04.10.2025 medium 2025 kotlin rust

Max water container from two heights

11. Container With Most Water medium blog post substack youtube

1.webp

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/1132

Problem TLDR

Max water container from two heights #medium #two-pointers

Intuition

Start with two pointer at max distance. Decrease distance by 1 by moving the lower height pointer. The length only decreases, so drop the lower height, it will not be better than the current.

Approach

  • if heights are equal move any pointer or both (to change minimum)

Complexity

  • Time complexity: \(O(n)\)

  • Space complexity: \(O(1)\)

Code


// 38ms
    fun maxArea(h: IntArray) =
        (h.lastIndex downTo 0).fold(0 to 0) { (r,i), l ->
            max(r,l*min(h[i],h[i+l])) to if (h[i]<h[i+l]) i+1 else i
        }.first


// 1ms
    pub fn max_area(h: Vec<i32>) -> i32 {
        (0..h.len()).rev().fold((0,0),|(r,i),l|
            (r.max(l as i32*h[i].min(h[i+l])),i+((h[i]<h[i+l])as usize))).0
    }