蠡口84. Largest Rectangle in Histogram

Meaning of the questions: Given an array represents a histogram in the height of each column, each column width is 1, find the largest rectangular area of ​​the histogram.

This question was first thought see DP, with a two-dimensional array of rectangles area between the i ~ j, then traversed again to obtain the maximum search area, the time complexity is O (n- 2 ). This is time out the code is as follows:

class Solution (Object):
     DEF largestRectangleArea (Self, Heights):
         "" " 
        : type Heights: List [int] 
        : rtype: int 
        " "" 
        n- = len (Heights)
         IF n-== 0: return (0)
         # . 1 ) initialization matrix dp: dp [i] [j] denotes heights [i: (j +) 1] between the shortest height of the column 
        dp = [[0 for J in Range (n-)] for I in Range (n-) ]
         # 2) where the boundary processing 
        for I in Range (n-): 
            DP [I] [I] = Heights [I]
             IFI <. 1-n-: DP [I] [I +. 1] = min (Heights [I], Heights [I +. 1 ])
         # . 3) to establish recursion relation: note the recursive obliquely from the upper right diag 
        # DP [i] [j] value should be dp [i + 1] [j -1], heights [i] and the heights [j] of the three minimum 
        for J in Range (2 , n-):
             for I in Range (N- J): 
                dp [I] [I + J] = min (dp [I +. 1] [I + J-. 1], Heights [I], Heights [I + J])
         # . 4) traversing dp matrix search maximum, heights [i: (j + 1)] is a rectangular area of DP [I] [J] * (I-J +. 1) 
        ANS = 0
         for I in Range (n-):
             for J in Range (I, the n-): 
                ANS=max(ans,dp[i][j]*(j-i+1))
        return(ans)

Below is O (n) solution, used the monotonous stack (the end of this monotonous stack of articles is very good: https://zhuanlan.zhihu.com/p/26465701 ), where the solution in full accordance with basketwang (link) on Youtube ( https://www.youtube.com/watch?v=KkJrGxuQtYo ). The idea is for each column IDX, to find the largest rectangle comprising (IDX) in all its parts, the maximum of the histogram rectangle required must be equal to max {largest rectangle (idx)}. Focus:! ! ! For idx column, which contains the maximum of all the rectangular portion (idx) the height of left and right sides of the column must be greater than or equal to the height of the column idx! ! ! Then the next task is to find a rectangular (IDX) in the left and right sides of the pillar, the area of a rectangle of (i) is the heights [idx] (high rectangular) multiplied by the left and right from the border (rectangle width). Rectangle i left / right boundary is actually a first [idx] after small (left) / the front (right) vectors in a number of heights idx front / back ratio of heights , as shown below:

    1            
    1   1   1    
    1   1   1    
...

 

1 ... 1 ... 1   ...
    1   1   1 1  
  1 1   1   1 1  
  1 1   1   1 1  
  left left+1   idx   right-1 right  

If we use a monotonically increasing stack (as the name implies, is Heights [top element]> = heights [element stack bottom]),

1) establish a monotonically increasing stack: If heights [top element +1]> = heights [top element], we put (the top element +1) push into the stack, in order to maintain a monotonically increasing property;

2) looking left and right hands: When we encounter heights [top element +1] <When [top element] heights, then we find the right pointer. Where is the left pointer in it? Remember, the stack is a monotonically increasing stack, which is the heights [top element]> = heights [a former top of the stack elements], so that left the previous element is the top of the stack (Note that there may have duplicate numbers of cases, using a while loop repeats skip numbers, see the code);

3) calculate the current maximum rectangular top element area: the area of a rectangle (the top element) is = heights [top element] * [right- (left + 1 )];

4) the calculated maximum rectangular area of a top element: In this case a rectangular area (top element) is computed once, next to pop it out, the maximum area rectangle is computed by a top element, this time right pointer Do not move, because it is still possible that the right boundary of the biggest rectangular;

5) The last remaining part of the deal: When all the elements have been to stack heights (some may have been after the stack), the stack is not empty, then the right side of the rectangle of the largest remaining elements should be mystack [-1] +1, it still left the previous element

class Solution (Object):
     DEF largestRectangleArea (Self, Heights):
         "" " 
        : type Heights: List [int] 
        : rtype: int 
        " "" 
        n- = len (Heights)
         # determines extreme values 
        IF n-== 0: return ( 0)
         # initialization monotone stack, and the right pointer, the final answer to the need to return 
        myStack = [] 
        right, ANS = 0,0
         # into circulation 
        the while right <n-: # right pointer can not exceed the length of the heights 
            # maintenance of monotonically increasing 
            IF len ( myStack) == 0 or Heights [right]> Heights = [myStack [-1 ]]:
                mystack.append (right) 
                right +. 1 =
             # Looking left, right pointer 
            else :
                 # when entering else, we have found the right position of the pointer, because this time Heights [right] <Heights [myStack [-1]] 
                # pop the top element and recorded for later calculating the area 
                IDX = mystack.pop ()
                 # repeating the previous figures when duplicate numbers, we can skip, such as the rectangular coordinate corresponding to the maximum is the same as 
                the while len ( myStack)> 0 and Heights [idx] == Heights [myStack [-1 ]]: mystack.pop ()
                 # when the stack is not empty when, left of the current stack top element, idx is not pop out before, stack the preceding element 
                # when the stack is empty, there is no number left heights smaller than the heights [idx], because the left front of the left edge of a rectangle, so it should be -1 
                # Why be alone when the stack is empty when discuss? Because we have all the elements of the stack is greater than 0
                # Is not initialized to -1 when the stack into the stack, we can not discuss here alone? Not! A height of the rectangle will be taken to the next heights [-1], the height of which is not; secondly next stack is still empty, left fail to mystack [-1] being given 
                left = -1 IF len (myStack ) == 0 the else myStack [-1 ] 
                ANS = max (ANS, Heights [IDX] * (. 1-right-left ))
                 # Note here is not updated right 
        # If the stack is empty, so that the element has been processed, return the results 
        IF len (myStack) == 0: return (ANS)
         # otherwise, this time the stack is monotonous, all remaining rectangle right border should be the top element +1 
        right = myStack [-1] +1 the while myStack: 
            IDX = mystack.pop () 
            left = -1 IF len (myStack) == 0
        else mystack[-1]
            ans=max(ans,heights[idx]*(right-left-1))
        return(ans)

 

Guess you like

Origin www.cnblogs.com/Leisgo/p/11696176.html