In this post, we will solve HackerRank Minimum Loss Problem 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.
Example
price = [20, 15, 8, 2, 12]
Her minimum loss is incurred by purchasing in year 2 at price[1] = 15 and reselling in year 5 at price[4] = 12. Return 15- 12 = 3.
Function Description
Complete the minimumLoss function in the editor below.
minimumLoss has the following parameter(s):
- int price[n]: home prices at each year
Returns
- int: the minimum loss possible
Input Format
The first line contains an integer n, the number of years of house data.
The second line contains n space-separated long integers that describe each price[i].
Sample Input 0
3 5 10 3
Sample Output 0
2
Explanation 0
Lauren buys the house in year 1 at price [0] = 5 and sells it in year 3 at price[2] = 3 for a minimal loss of 5-32.
Sample Input 1
5 20 7 8 2 5
Sample Output 1
2
Explanation 1
Lauren buys the house in year 2 at price[1] = 7 and sells it in year 5 at price[4] = 5 for a minimal loss of 7-5 = 2.

Minimum Loss C Solution
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <limits.h>
struct node {
long long val;
struct node *left;
struct node *right;
};
typedef struct node node_t;
static node_t *
init_tree(long long val)
{
node_t *tree = NULL;
tree = calloc(1, sizeof(node_t));
tree->val = val;
return tree;
}
static void
insert(node_t *tree, node_t *t, long long *min)
{
if (tree->val > t->val) {
*min = tree->val;
if (tree->left) {
return insert(tree->left, t, min);
} else {
tree->left = t;
return;
}
} else {
if (tree->right) {
return insert(tree->right, t, min);
} else {
tree->right = t;
}
}
return;
}
int main() {
long long unsigned min_loss = ULONG_MAX;
long long N;
long long i, val, min;
node_t *temp = NULL;
node_t *tree = NULL;
scanf("%lld", &N);
for (i = 0; i < N; i++) {
scanf("%lld", &val);
min = -1;
if (i == 0) {
tree = init_tree(val);
continue;
}
temp = calloc(1, sizeof(node_t));
temp->val = val;
insert(tree, temp, &min);
if ((min != -1) && (min_loss > (min - val))) {
min_loss = min - val;
}
}
printf("%lld\n", min_loss);
return 0;
}
Minimum Loss C++ Solution
#include <bits/stdc++.h>
using namespace std;
#define on(s, j) ((s >> j) & 1)
#define lowbit(s) (s & (-s))
#define dbg(x) cerr << #x << " : " << (x) << " "
#define print(x) cerr << (x) << " "
#define newline cerr << "\n"
typedef long long ll;
inline int lsb(ll x) {return __builtin_ctzll(x);}
inline int gi() {int x; scanf("%d", &x); return x;}
inline ll gll() {ll x; scanf("%lld", &x); return x;}
inline int msb(ll x) {return 63-__builtin_clzll(x);}
template <class T>
void debug(T a, T b) {
cerr << "[";
for (T i = a; i != b; ++i) {
if (i != a) cerr << ", ";
cerr << *i;
}
cerr << "]\n";
}
const int N = 200010;
ll p[N];
int main() {
// freopen("input.in", "r", stdin);
// freopen("output.out", "w", stdout);
int n = gi();
for (int i = 0; i < n; i++) {
p[i] = gll();
}
ll ans = (ll)1e17;
set <ll> st;
for (int i = n - 1; i >= 0; i--) {
if (i == n - 1) {
st.insert(p[i]);
} else {
set <ll> :: iterator it = st.lower_bound(p[i]);
if (it != st.begin()) {
it--;
ans = min(ans, p[i] - *it);
}
st.insert(p[i]);
}
}
printf("%lld\n", ans);
}
Minimum Loss C Sharp Solution
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution
{
static void Main(String[] args)
{
int n = Int32.Parse(Console.ReadLine());
double[] price = Console.ReadLine().Split(' ').Select(double.Parse).ToArray();
Console.WriteLine(DisplayMinLoss(price));
}
private static double DisplayMinLoss(double[] price)
{
List<double> sortedList = price.ToList();
sortedList.Sort();
double minimum = sortedList.Sum();
for (int i = 0; i < sortedList.Count - 1; i++)
{
if ((sortedList[i + 1] - sortedList[i]) < minimum && Array.IndexOf(price, sortedList[i + 1]) < Array.IndexOf(price, sortedList[i]))
{
minimum = sortedList[i + 1] - sortedList[i];
}
}
return minimum;
}
}
Minimum Loss Java Solution
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
class Result {
public static int minimumLoss(List<Long> price) {
// Write your code here
HashMap<Long,Integer> h=new HashMap<>();
for(int i=0;i<price.size();i++)
{
h.put(price.get(i),i);
}
Collections.sort(price);
long min=Integer.MAX_VALUE;
for(int i=1;i<price.size();i++)
{
if(h.get(price.get(i))<h.get(price.get(i-1)) && (price.get(i)-price.get(i-1))<min)
{
min=price.get(i)-price.get(i-1);
}
}
return (int)min;
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int n = Integer.parseInt(bufferedReader.readLine().trim());
List<Long> price = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
.map(Long::parseLong)
.collect(toList());
int result = Result.minimumLoss(price);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedReader.close();
bufferedWriter.close();
}
}
Minimum Loss JavaScript Solution
function processData(input) {
var x = input.split("\n");
var n = Number(x[0]);
var s = x[1].split(' ');
var a = {};
var loss = Infinity;
var matched = false;
for (var i=0; i < s.length; i++) {
s[i] = Number(s[i]);
if (a[s[i]] !== undefined) {
matched = true;
break;
}
a[s[i]] = i;
}
if (matched) {
return 0;
}
var compr = function (x, y) {
return y-x;
}
s.sort(compr);
var x,y;
for (var i=1; i < s.length; i++) {
x = s[i-1];
y = s[i];
if (a[x] < a[y]) {
loss = (loss > x - y) ? x-y : loss;
}
}
console.log(loss);
}
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});
Minimum Loss Python Solution
n = int(input().strip())
numbers = list(map(int,input().strip().split()))
nums = list(numbers)
nums.sort()
minCost = sum(nums)
for i in range(1,n):
if (nums[i]-nums[i-1] < minCost) and (numbers.index(nums[i]) < numbers.index(nums[i-1])):
minCost = nums[i]-nums[i-1]
print(minCost)