Nine Chapters count judges Net-original websitehttp://www.jiuzhang.com/problem/43/
Topics
A histogram () is given to find the largest matrix area included in the given histogram. The histogram can be represented by an array of integers, such as [2, 1, 5, 6, 2, 3]. Each straight block has a width of 1. The largest matrix area contained in is 10.
Answer
If for each straight square, find from it start to the left number first is smaller than it, and to the right number first is smaller than him, you can determine the vertical square is the shortest piece of the matrix of the maximum area. Using the data structure stack, save the increment sequence in the stack, traverse each number from left to right, let it go into the stack, pop out all >= number of the number before the stack, so as to keep the increment sequence in the stack. The top element of the stack after the pop is the number that is the first to the left number. The same way you can get to the right number the first number that is smaller than him. Time complexity O (n), spatial complexity O (n)
Interviewer Angle
Calculating the number of the first to the left or to the right for each number is larger or smaller than it is a typical application scenario for a data structure stack. This method is also used in the problem of "constructing Maxtree" in the nine chapters of the algorithm surface question 42. Therefore, you need to remember that in this case, the use of stacks can make time complexity and spatial complexity both O (n). The problem of the maximum matrix of the histogram is a very common problem in the interview, this topic wants everybody to carry on the thorough study, and the programming realizes.
Nine-chapter algorithm surface question 43 The maximum matrix in the histogram