Arranging Skyscrapers

4.6

5 votes
Easy-Medium
Problem

Megha is one of the most talented architects in the industry. The government is planning to construct a new line of skyscrapers and has tasked Megha with designing it's layout. The following are the requirements which have been specified:

  • There are N skyscrapers with specified heights h1,h2,....hn
  • The skyscrapers must be arranged in a straight line in some order
  • One of the skyscrapers is the main building and needs to be in the center.
  • There are two skyscrapers which are trade centers and need to placed at the ends so that they are easily accessible to outsiders.

Note: If the number of skyscrapers is even, the main building can be at either of the centers.

To make the arrangement look good, Megha wants to minimize the irregularity in heights between consecutive skyscrapers. Formally, she wants to minimize the sum of the absolute height differences of adjacent skyscrapers. Your task is to help her find the optimal arrangement which satisfies the given requirements.

Input:

  • First line contains an integer N representing number of skyscrapers
  • Second line contains N space separated integers h1,h2,h3... hn. The first integer represents the height of the main building. The second and third integers represent the height of the two trade centers. The remaining integers represent the heights of the other skyscrapers.

Output:

  • One line containing an integer which is the minimum possible sum of absolute differences between adjacent skyscrapers among all possible arrangements which satisfy the requirements given in the problem statement.

Constraints:

  • 5 <= N <= 50
  • 10 <= hi <= 100
Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

One optimal way to line up is 17, 12, 13, 10, 11 making the sum of the absolute differences 5 + 1 + 3 + 1 = 10.

Editor Image

?