/*
* minimum loss
*
* read Java TreeSet floor method:
* https://www.tutorialspoint.com/java/util/treeset_floor.htm
*
* use C# List<T> BinarySearch, Insert API
* https://msdn.microsoft.com/en-us/library/w4e7fxsh(v=vs.110).aspx
*
*
* The idea is to go over each house in the reverse order, add one by
* one into the List object, but
* the List iscannot alsobe a binary search tree. How to
do it? To maintain the* binaryUsing searchBinarySearch tree,to
find the position first (Time *complexity using
BinarySearch to find the position* firstO(n)), similar to Java TreeSet class floor method, but Insert
* meanwhiletakes O(n) time.
* Meanwhile, update minimum loss value if the insertion position
* is not the smallest one in the tree.
*
* Go over each house once, each time, binary search will take
* O(logn) time, but Insert takes O(n). Therefore, the final
* time complexity should be O(n^2), not O(nlogn).
*/
private static Int64 MinimumLossCal(int n, Int64[] prices)
{
List<Int64> data = new List<Int64>();
Int64 minLoss = Int64.MaxValue;
for (int i = n - 1; i >= 0; i--)
{
Int64 curPrice = prices[i];
var index = data.BinarySearch(curPrice);
if (index < 0)
{
int pos = ~index;
if (pos > 0)
{
Int64 newDiff = curPrice - data[pos - 1];
minLoss = (newDiff < minLoss) ? newDiff : minLoss;
}
data.Insert(pos, curPrice);
}
// if there is one in the binary search tree, then no need to insert the duplicate one in the tree.
}
return minLoss;
}
Fix the comment above the function MinimuLossCal, time complexity should be O(n^2), not O(nlogn).
Jianmin Chen
- 2.5k
- 2
- 29
- 52
Time complexity analysis of using List<T> should be O(n^2), not O(nlogn). Just make the correction.
Jianmin Chen
- 2.5k
- 2
- 29
- 52