Nine-chapter algorithm surface question 43 The maximum matrix in the histogram

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.