In this HackerRank Minimum Loss 1 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.

HackerRank Minimum Loss 1 problem solution


Problem solution in Python.

#!/bin/python3

import math
import os
import random
import re
import sys

#
# Complete the 'minimumLoss' function below.
#
# The function is expected to return an INTEGER.
# The function accepts LONG_INTEGER_ARRAY price as parameter.
#

def minimumLoss(price):
    # Write your code here
    s = sorted (enumerate (price), key = lambda kv : kv[1])
    print(s)
    return min ((s[i+1][1] - s[i][1] for i in range (len(s) - 1) if s[i+1][0] < s[i][0]))
    


if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input().strip())

    price = list(map(int, input().rstrip().split()))

    result = minimumLoss(price)

    fptr.write(str(result) + '\n')

    fptr.close()



Problem solution in Java.

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 {

    /*
     * Complete the 'minimumLoss' function below.
     *
     * The function is expected to return an INTEGER.
     * The function accepts LONG_INTEGER_ARRAY price as parameter.
     */
     
     private static class Node {
        final long val;
        Node left;
        Node rigth;
        
        public Node(long val) {
            this.val = val;
        }
     }
     
    private static long put(Node head, long val) {
        Node current = head;
        Node parent = null;
        long min = Long.MAX_VALUE;
        int direction = 0;

        while (current != null) {
            parent = current;
            if (val > current.val) {
                min = Math.min(min, val - current.val);
                current = current.rigth;
                direction = 1;
            } else {
                current = current.left;
                direction = -1;
            }
        }

        if (direction == 1) {
            parent.rigth = new Node(val);
        } else {
            parent.left = new Node(val);
        }

        return min;
    }

    public static int minimumLoss(List<Long> price) {
        long min = Long.MAX_VALUE;
        Node head = new Node(price.get(price.size() - 1));

        for (int i = price.size() - 2; i >=0; i--) {
            long candidate = put(head, price.get(i));
            if (candidate < min) {
                min = candidate;
            }
        }

        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();
    }
}


Problem solution in C++.

#include <bits/stdc++.h>

using namespace std;

string ltrim(const string &);
string rtrim(const string &);
vector<string> split(const string &);

/*
 * Complete the 'minimumLoss' function below.
 *
 * The function is expected to return an INTEGER.
 * The function accepts LONG_INTEGER_ARRAY price as parameter.
 */

int minimumLoss(vector<long> price) {
  set<long> prev_prices;
  long min_v = 1e18 + 10;
  for(auto v : price){
    auto it = prev_prices.upper_bound(v);
    if(it != prev_prices.end()){
      min_v = min(min_v, *it - v);
    }
    prev_prices.insert(v);
  }
  return min_v;
}

int main()
{
    ofstream fout(getenv("OUTPUT_PATH"));

    string n_temp;
    getline(cin, n_temp);

    int n = stoi(ltrim(rtrim(n_temp)));

    string price_temp_temp;
    getline(cin, price_temp_temp);

    vector<string> price_temp = split(rtrim(price_temp_temp));

    vector<long> price(n);

    for (int i = 0; i < n; i++) {
        long price_item = stol(price_temp[i]);

        price[i] = price_item;
    }

    int result = minimumLoss(price);

    fout << result << "\n";

    fout.close();

    return 0;
}

string ltrim(const string &str) {
    string s(str);

    s.erase(
        s.begin(),
        find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)))
    );

    return s;
}

string rtrim(const string &str) {
    string s(str);

    s.erase(
        find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(),
        s.end()
    );

    return s;
}

vector<string> split(const string &str) {
    vector<string> tokens;

    string::size_type start = 0;
    string::size_type end = 0;

    while ((end = str.find(" ", start)) != string::npos) {
        tokens.push_back(str.substr(start, end - start));

        start = end + 1;
    }

    tokens.push_back(str.substr(start));

    return tokens;
}


Problem solution in C.

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>


typedef struct {
    long int val;
    int pos;
} node_t;

int cmpfunc(const void * a, const void * b)
{
    long int diff = ((node_t*)b)->val - ((node_t*)a)->val;
    if(diff < 0)
        return -1;
    else if(diff > 0)
        return 1;
    return 0;
}

int minimumLoss(int price_size, long int* price)
{
    node_t* pricenodes = malloc(sizeof(node_t)*price_size);

    for(int i=0; i<price_size; ++i) {
        pricenodes[i].val = price[i];
        pricenodes[i].pos = i;
    }

    // Reverse sort
    qsort(pricenodes, price_size, sizeof(*pricenodes), cmpfunc);

    long int curmin = -1;

    for(int i=1; i<price_size; ++i)
        if(pricenodes[i].pos > pricenodes[i-1].pos)
            if(-1 == curmin || curmin > pricenodes[i-1].val - pricenodes[i].val)
                curmin = pricenodes[i-1].val - pricenodes[i].val;

    return curmin;
}

int main() {
    int n; 
    scanf("%i", &n);
    long int *price = malloc(sizeof(long int) * n);
    for (int price_i = 0; price_i < n; price_i++) {
       scanf("%li",&price[price_i]);
    }
    int result = minimumLoss(n, price);
    printf("%d\n", result);
    return 0;
}