這項任務的另一種O(n)的解決方案可以通過使用本地的最小和最大發現最大值和最小值之間的最佳尊重(利潤)明知最大應該有更大然後指數分鐘來完成。我們還需要查看以前最好的本地分鐘(C#實現)。
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]);
}
在您的例子 「1 3 1 2 4」 的結果應該是9中未7 :)最大價爲4不2. 「1 4 1 2 3」 將顯示您的算法更好:)例如在 – 2013-05-23 01:03:12
, 1 3 1 2 4,爲什麼最高股價是在第2天?是不是最後一天有最高的價格? – 2015-03-29 20:11:20
幾乎沒有更新,現在最多隻能購買和出售N次,那麼這種新情況的解決方案是什麼? – uniquephase 2015-10-02 19:44:02