![](/img/trans.png)
[英]PHP array_slice or equivalent on array of arrays that are keyed by ID
[英]PHP's array_slice vs Python's splitting arrays
我正在嘗試常見的“ MaxProfit”編程挑戰。 它基本上是這樣的:
給定零索引數組A(包含N個整數),其中N個整數包含連續N天的股票價格,則返回該期間一次交易的最大可能利潤。
避免了幼稚的蠻力嘗試,我對我提出的PHP算法感到非常滿意:
public function maxProfit($prices)
{
$maxProfit = 0;
$key = 0;
$n = count($prices);
while ($key < $n - 1) {
$buyPrice = $prices[$key];
$maxFuturePrice = max( array_slice($prices, $key+1) );
$profit = $maxFuturePrice - $buyPrice;
if ($profit > $maxProfit) $maxProfit = $profit;
$key++;
}
return $maxProfit;
}
但是,測試了我的解決方案后,它似乎在性能方面表現不佳,甚至在O(n 2 )時間內也是如此。
我做了一些閱讀,發現了一個非常相似的python解決方案。 Python具有一些非常方便的數組功能,可以使用a a[s : e]
語法拆分數組,這與PHP中我使用array_slice
函數的方式不同。 我認為這一定是瓶頸,所以我做了一些測試:
PHP array_slice()
$n = 10000;
$a = range(0,$n);
$start = microtime(1);
foreach ($a as $key => $elem) {
$subArray = array_slice($a, $key);
}
$end = microtime(1);
echo sprintf("Time taken: %sms", round(1000 * ($end - $start), 4)) . PHP_EOL;
結果:
$ php phpSlice.php
Time taken: 4473.9199ms
Time taken: 4474.633ms
Time taken: 4499.434ms
Python a [s:e]
import time
n = 10000
a = range(0, n)
start = time.time()
for key, elem in enumerate(a):
subArray = a[key : ]
end = time.time()
print "Time taken: {0}ms".format(round(1000 * (end - start), 4))
結果:
$ python pySlice.py
Time taken: 213.202ms
Time taken: 212.198ms
Time taken: 215.7381ms
Time taken: 213.8121ms
array_slice()
效率比Python低20倍? maxProfit
算法在O(N)時間內運行? 編輯我意識到我上面的實現實際上不是O(N),但是我的問題仍然在於切片數組的效率。 max
都不超過數組的一半。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.