LeetCode - Algorithms
  • Introduction
  • 1. Two Sum
  • 2. Add Two Numbers
  • 3. Longest Substring Without Repeating Characters
  • 4. Median of Two Sorted Arrays
  • 5. Longest Palindromic Substring
  • 6. ZigZag Conversion
  • 7. Reverse Integer
  • 8. String to Integer (atoi)
  • 9. Palindrome Number
  • 10. Regular Expression Matching
  • 11. Container with Most Water
  • 12. Integer to Roman
  • 13. Roman to Integer
  • 14. Longest Common Prefix
  • 15. 3Sum
  • 16. 3Sum Closest
  • 17. Letter Combinations of a Phone Number
  • 18. 4Sum
  • 19. Remove Nth Node From End of List
  • 20. Valid Parentheses
  • 21. Merge Two Sorted Lists
  • 22. Generate Parentheses
  • 23. Merge k Sorted Lists
  • 24. Swap Nodes in Pairs
  • 25. Reverse Nodes in k-Group
  • 26. Remove Duplicates from Sorted Array
  • 27. Remove Element
  • 28. Implement strStr()
  • 29. Divide Two Integers
  • 30. Substring with Concatenation of All Words
  • 31. Next Permutation
  • 32. Longest Valid Parentheses
  • 33. Search in Rotated Sorted Array
  • 34. Search for a Range
  • 35. Search Insert Position
  • 36. Valid Sudoku
  • 37. Sudoku Solver
  • 38. Count and Say
  • 39. Combination Sum
Powered by GitBook
On this page
  • Problem
  • Analysis
  • Code

11. Container with Most Water

Previous10. Regular Expression MatchingNext12. Integer to Roman

Last updated 6 years ago

Problem

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 and n is at least 2.

Related Topics:

Array Two Pointers

Analysis

一个容器所能装的水量为: length * min(height[l] , height[r])。

l 与 r 分别从两端开始,向中间遍历。当 height[l] < height[r] 时,最小边为 l,移动 r 并不能扩大面积,所以移动 l。反之,移动 r 即可。

Code

class Solution {

    fun maxArea(height: IntArray): Int {

        var max = 0
        var l = 0
        var r = height.size - 1

        while (l < r) {
            max = maxOf(max, (r - l) * if (height[l] < height[r]) height[l++] else height[r--])
        }

        return max
    }
}