#11 Container With Most Water

#11 Container With Most Water

Problem Description

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.

The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example:

Input: [1,8,6,2,5,4,8,3,7]
Output: 49

Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/container-with-most-water
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

Problem-solving ideas

Method using two pointers, a pointer is provided in the left most \ (I \) , the right-most set pointer \ (J \) . Each time the movement of both the small value, until the two meet pointer.

Explanation:

For pointer \ (i, j \) surrounded by the capacity of the container we referred to as \ ((I, J) \) , then the initial state is \ ((1,7) \) .

Why we can move the pointer short of it? We can look at our state every time you move the pointer ignored: For the first move, we will not calculate \ ((1,8), (1,6), ..., (1,8), (1, 3) \) . For such a state is ignored, the length of the base must be smaller than \ ((1,7) \) , and the maximum height of the container may be only \ (1 \) , indicating that the volume of these states must be ignored than \ ( (1,7) \) small (base length becomes smaller, or the same hypervariable small rectangular area becomes smaller).

Thereby prove the correctness of the algorithm, the results obtained in the case of minimizing the amount of computation.

Time complexity: \ (O (n-) \) , successively traverse

Space complexity: \ (O (1) \) , you can just save the maximum volume

Code explanation

Relatively simple, not interpretation

Github

Guess you like

Origin www.cnblogs.com/LvBaiYang/p/12546846.html