I was asked this question while interviewing for a startup and saw this again in the recent contest at
Code Sprint:systems
**The question :
You are
Another O(n) solution for this task can be done by using local minimum and maximum finding the best deference (profit) between max and min knowing that max should have greater index then min. We also need to look at previous best local min (C# implementation).
public int[] GetBestShareBuyingStrategy(int[] price)
{
var n = price.Length;
if (n <= 1)
return null;
var profit = 0;
var min = 0;
var max = 0;
var lmin = 0;
for (var i = 1; i < n; i++)
{
var lmax = i;
var lp = price[lmax] - price[lmin];
if (lp <= 0)
{
lmin = i;
}
else
{
var tp = price[lmax] - price[min];
if (lp > tp && lp > profit)
{
min = lmin;
max = lmax;
profit = lp;
}
else if (tp > profit)
{
max = lmax;
profit = tp;
}
}
}
return profit > 0
? new [] {min, max}
: null;
}
[Test]
[TestCase(new[] { 10, 9, 8, 7, 3 })]
[TestCase(new[] { 5, 5, 5, 5, 5 })]
[TestCase(new[] { 5, 4, 4, 4 })]
[TestCase(new[] { 5, 5, 3, 3 })]
public void GetBestShareBuyingStrategy_When_no_sense_to_buy(int[] sharePrices)
{
var resultStrategy = GetBestShareBuyingStrategy(sharePrices);
Assert.IsNull(resultStrategy);
}
[Test]
[TestCase(new[] { 10, 8, 12, 20, 10 }, 1, 3)]
[TestCase(new[] { 5, 8, 12, 20, 30 }, 0, 4)]
[TestCase(new[] { 10, 8, 2, 20, 10 }, 2, 3)]
[TestCase(new[] { 10, 8, 2, 20, 10 }, 2, 3)]
[TestCase(new[] { 10, 2, 8, 1, 15, 20, 10, 22 }, 3, 7)]
[TestCase(new[] { 1, 5, 2, 7, 3, 9, 8, 7 }, 0, 5)]
[TestCase(new[] { 3, 5, 2, 7, 3, 9, 8, 7 }, 2, 5)]
public void GetBestShareBuyingStrategy_PositiveStrategy(int[] sharePrices, int buyOn, int sellOn)
{
var resultStrategy = GetBestShareBuyingStrategy(sharePrices);
Assert.AreEqual(buyOn, resultStrategy[0]);
Assert.AreEqual(sellOn, resultStrategy[1]);
}