Created
November 21, 2016 22:26
-
-
Save jianminchen/63c1ed68999f78a72250372eb58a6953 to your computer and use it in GitHub Desktop.
Minimum Cost - HackerRank codesprint #2 - use SortedSet in C#, still timeout on some test cases, score 17.5 of 20
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace minimumLoss | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
process(); | |
//testcase2(); | |
} | |
private static void process() | |
{ | |
int n = int.Parse(Console.ReadLine()); | |
Int64[] prices = new Int64[n]; | |
string[] arr = Console.ReadLine().Split(' '); | |
prices = Array.ConvertAll(arr, Int64.Parse); | |
Console.WriteLine(minimumLossCal(n, prices)); | |
} | |
private static void testcase2() | |
{ | |
Int64[] prices = new Int64[5] { 20, 7, 8, 2, 5 }; | |
Console.WriteLine(minimumLossCal(5, prices)); | |
} | |
private static void testcase3() | |
{ | |
Int64[] prices = new Int64[4] { 2, 3, 4, 1 }; | |
Console.WriteLine(minimumLossCal(4, prices)); | |
} | |
/* | |
* minimum loss | |
* finished time: 4:02pm | |
* | |
* read Java TreeSet floor method: | |
* https://www.tutorialspoint.com/java/util/treeset_floor.htm | |
* | |
* http://stackoverflow.com/questions/4872946/linq-query-to-select-top-five | |
* | |
* http://stackoverflow.com/questions/11549580/find-key-with-max-value-from-sorteddictionary | |
* | |
* http://stackoverflow.com/questions/1635497/orderby-descending-in-lambda-expression | |
* | |
* timeout issue - try to find LINQ has a solution or not | |
* http://stackoverflow.com/questions/14675108/sortedset-sortedlist-with-better-linq-performance | |
* | |
* | |
*/ | |
private static Int64 minimumLossCal(int n, Int64[] prices) | |
{ | |
SortedSet<Int64> data = new SortedSet<Int64>(); | |
Int64 minLoss = Int64.MaxValue; | |
for (int i = n - 1; i >= 0; i--) | |
{ | |
var smaller = data.Where(p =>p < prices[i]).OrderByDescending(p=>p ).Take(1); | |
if (smaller.Any()) | |
{ | |
Int64 newDiff = prices[i] - smaller.Last(); | |
minLoss = (newDiff < minLoss) ? newDiff : minLoss; | |
} | |
data.Add(prices[i]); | |
} | |
return minLoss; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment