Skip to content

Instantly share code, notes, and snippets.

@bhavjot
Created March 10, 2017 05:46
Show Gist options
  • Save bhavjot/62574c21aabc5ce8ee692b1eb3eb3b74 to your computer and use it in GitHub Desktop.
Save bhavjot/62574c21aabc5ce8ee692b1eb3eb3b74 to your computer and use it in GitHub Desktop.
Minimum Loss - Sorted Set - Perfect Solution - Hacker Rank
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {
static void Main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */
int n = Convert.ToInt32(Console.ReadLine());
string[] arr_temp = Console.ReadLine().Split(' ');
long[] arr = Array.ConvertAll(arr_temp,Int64.Parse);
long min = Int64.MaxValue;
SortedSet<Int64> sortedPriceList = new SortedSet<Int64>();
for (int i=n-1;i>=0;i--)
{
Int64 currentPrice = arr[i];
long minVal = currentPrice - min +1;
long maxVal = currentPrice -1;
if(minVal<=maxVal)
{
var smallerSet = sortedPriceList.GetViewBetween(minVal,maxVal);
if(smallerSet.Any())
{
min = currentPrice - smallerSet.Max();
}
}
sortedPriceList.Add(currentPrice);
}
Console.Write(min);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment