We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
  • HackerRank Home
  • |
  • Prepare
  • Certify
  • Compete
  • Apply
  • Hiring developers?
  1. Prepare
  2. Functional Programming
  3. Functional Structures
  4. John and Fences

John and Fences

Problem
Submissions
Leaderboard
Discussions

John's house has bizarre fencing. There are N fences. Though the contiguous fences have the constant width of 1 unit but their height varies. Height of these fences is represented by array H = [h1, h2... hN].

John loves his fences but has to finally bow down to his wife's repeated requests of replacing them with the regular fences. Before taking them down, John wants to keep some part of the fences as souvenir. He decides to carve out the largest rectangular area possible where the largest rectangle can be made of a number of contiguous fence. Note that sides of the rectangle should be parallel to X and Y axis.

Let's say there are 6 fences, and their height is, H = [2, 5, 7, 4, 1, 8]. Then they can be represented as

                   __
8         __      |  |
7        |  |     |  |
6      __|  |     |  |
5     |  |  |__   |  |
4     |  |  |  |  |  |
3   __|  |  |  |  |  |
2  |  |  |  |  |__|  |
1  |__|__|__|__|__|__|
    h1 h2 h3 h4 h5 h6

Some possible carvings are as follow:

  • If we carve rectangle from h1, h2 and h3 then we can get the max area of 2x3 = 6 units.
  • If we carve rectangle from h3, h4, h5 and h6, then max area is 4x1 = 4 units.
  • If we carve rectangle from h2, h3 and h4, then max area is 4x3 = 12, which is also the most optimal solution for this case.

Input
First line will contain an integer N denoting the number of fences. It will be followed by a line containing N space separated integers, h1 h2 ... hN, which represents the height of each fence.

Output
Print the maximum area of rectangle which can be carved out.

Note

Constraints
1 ≤ N ≤ 105
1 ≤ hi ≤ 104

Sample Input

6
2 5 7 4 1 8

Sample Output

12

Explanation
John can carve a rectangle of height 4 from fence #2, #3 and #4, whose respective heights are 5, 7 and 4. So this will lead to a rectangle of area 3x4 = 12 units.


Tested by: Lalit Kundu

Author

tussharsingh13

Difficulty

Medium

Max Score

50

Submitted By

838

Need Help?


View discussions
View top submissions

rate this challenge

MORE DETAILS

Download problem statement
Download sample test cases
Suggest Edits
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Helpdesk
  • Careers
  • Terms Of Service
  • Privacy Policy

Cookie support is required to access HackerRank

Seems like cookies are disabled on this browser, please enable them to open this website

Join us

Create a HackerRank account

Be part of a 26 million-strong community of developers

Please signup or login in order to view this challenge

or
Already have an account?Log in