Hackerrank - Minimum Loss Solution
1 min read

Hackerrank - Minimum Loss Solution

Hackerrank - Minimum Loss Solution

Lauren has a chart of distinct projected prices for a house over the next several years. She must buy the house in one year and sell it in another, and she must do so at a loss. She wants to minimize her financial loss.

For example, the house is valued at  over the next  years. She can purchase the home in any year, but she must resell the house at a loss in one of the following years. Her minimum loss would be incurred by purchasing in year  at  and reselling in year  at .

Find and print the minimum amount of money Lauren must lose if she buys the house and resells it within the next  years.

Note: It's guaranteed that a valid answer exists.

Function Description

Complete the minimumLoss function in the editor below. It should return an integer that represents the minimum loss that can be achieved.

minimumLoss has the following parameter(s):

  • price: an array of integers that represent prices at each year

Input Format

The first line contains an integer , the number of years of house data.
The second line contains  space-separated long integers describing each .


  • All the prices are distinct.
  • A valid answer exists.


  • for  of the maximum score.

Output Format

Print a single integer denoting the minimum amount of money Lauren must lose if she buys and resells the house within the next  years.

Sample Input 0

5 10 3

Sample Output 0


Explanation 0

Lauren buys the house in year  at  and sells it in year  at  for a minimal loss of .

Sample Input 1

20 7 8 2 5

Sample Output 1


Explanation 1

Lauren buys the house in year  at  and sells it in year  at  for a minimal loss of .

Solution in Python

def minimumLoss(arr):
    s = sorted(enumerate(arr),key=lambda kv:kv[1])
    return min((s[i+1][1]-s[i][1] for i in range(len(s)-1) if s[i+1][0]<s[i][0]))
arr = list(map(int,input().split()))

Enjoying these posts? Subscribe for more

Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

That's okay. But without advertising-income, we can't keep making this site awesome.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add thepoorcoder.com to your ad blocking whitelist or disable your adblocking software.