Wednesday, May 29, 2013

Container with most water @ leetcode

微博:http://www.weibo.com/cathyhwzn

刷题必备书籍:Cracking the Coding Interview: 150 Programming Questions and Solutions
Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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. 

3 comments:

  1. 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)?

    ReplyDelete
    Replies
    1. Use 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)

      Delete
  2. Your prove is easy to understand, thanks :)

    ReplyDelete

Leetcode 316. Remove Duplicate Letters

 这道题表面问的是如何删除重复,实际在问如何从多个字符选取一个保留,从而让整个字符串按升序排列。那么策略就是对于高顺位的字符比如‘a',就要选靠前位置的保留,而低顺位字符如’z'则应该尽量选取靠后位置保留。 算法大概思路:每看到一个字符,我们要决定是否保留 1. ...