Source of the topic:
https://leetcode.com/problems/container-with-most-water/
Test Instructions Analysis:
Given an n-length non-0 array, the A1,A2,......, An,ai represents the height of the AI on the coordinate i. A container can be constructed with Ai,aj as high and I to J as the base. Then find out the maximum volume of water that can be contained in these containers (the container cannot be tilted). For example, the array [2,1], a total of 1 containers can be constructed, the four endpoint coordinates of the container is (0,0), (0,2), ((), (), then he can install the maximum water volume is (1-0) * = 1.
Topic Ideas:
It is not difficult to find that the size of the water volume is determined by the short height. The method of violence is to find out all the containers, calculate their water volume, compare them, and then get the maximum, the time complexity of this method is (O (n^2)). It's obviously going to be tle.
We take a serious look at the process, we start from the first height of the container wall, then we directly to the last height of the end of the wall, if A1 <= an, then the A1 as the beginning of the container is A1 * (n-1), A1 for the container wall of the largest container calculated. Then all cases with A1 as a wall do not need to be considered, then consider A2; Similarly, if A1 > An,an no longer consider, consider An-1, which is somewhat similar to the "pinch theorem". Compare AI and AJ (i<j) If AI <= aj,i++, no person J + + until I = = J. The time complexity of this algorithm is (O (n)).
Code (Python):
1 classsolution (object):2 defMaxarea (self, height):3 """4 : Type Height:list[int]5 : Rtype:int6 """7size = Len (height)#The size of height8MAXM = 0#record the most water9j =0TenK = size-1 One whileJ <K: A ifHEIGHT[J] <=Height[k]: -MAXM = max (Maxm,height[j] * (K-j)) -J + = 1 the Else: -MAXM = max (Maxm,height[k] * (K-j)) -K-= 1 - returnMaxm
View Code
Reprint Please specify source: http://www.cnblogs.com/chruny/p/4817787.html
[Leetcode] (python): 011-container with most water