微博:http://www.weibo.com/cathyhwzn
刷题必备书籍:Cracking the Coding Interview: 150 Programming Questions and Solutions
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.
First of all, to understand the problem. What it asks is, to find the maximun value of (i-j)*min(a_i, a_j). At the first , I only think of brute force solution which will cost O(n^2). Then I found a solution with linear cost. Set two pointers, point to begin and end. Move the pointer which points to the smaller element in array. The algorithm is simple, the hardest part is to prove the correctness of this algorithm.
Because the contain volume is decided by the shorter line between two.
Since i is lower than j, so there will be no jj < j that make the area from i,jj is greater than area from i,jso the maximum area that can benefit from i is already recorded.thus, we move i forward.
Since i is lower than j, so there will be no jj < j that make the area from i,jj is greater than area from i,jso the maximum area that can benefit from i is already recorded.thus, we move i forward.
your proof of the method might be wrong. what if [2,3,1000, 4] now, i points to 2, j points to 4. There exists a jj which points to 1000 that makes the area (i, jj) a lot larger than (i, j)?
ReplyDeleteUse your case, area (i,jj) is equals to 2*2 = 4, (jj,j) is equals to 1*4 = 4. A(i,jj) is not larger than A(i,j)
DeleteYour prove is easy to understand, thanks :)
ReplyDelete