Created
November 21, 2016 22:09
-
-
Save jianminchen/3e978465798afbd7d611e90a8ad7af0c to your computer and use it in GitHub Desktop.
HackerRank - woman codesprint #2 - minimum cost - timeout issue
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 | |
*/ | |
private static Int64 minimumLossCal(int n, Int64[] prices) | |
{ | |
SortedDictionary<Int64, Int32> data = new SortedDictionary<Int64, Int32>(); | |
Int64 minLoss = Int64.MaxValue; | |
for (int i = n - 1; i >= 0; i--) | |
{ | |
var smaller = data.Where(p => p.Key < prices[i]).OrderByDescending(p=>p.Key).Take(1); | |
if (smaller.Any()) | |
{ | |
Int64 newDiff = prices[i] - smaller.Last().Key; | |
minLoss = (newDiff < minLoss) ? newDiff : minLoss; | |
} | |
data.Add(prices[i], i); | |
} | |
return minLoss; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment