Problem
Given n non-negative A, where A[i] represents a vertical line with height A[i]. 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.Algorithm
Let two points L scans from left and R scans from right. Until L > R, we compute the current area formed by L and R. If it is larger than maximum area found so far, we update the maximum area. Then we move the shorter bar towards the center. Since, L or R is moving towards the center, the distance between them, i.e. the width of the rectangle is decreasing. If we want to find a larger rectangle, we must improve the shorter bar.
Picture comes from here.
No comments:
Post a Comment