一些背景
我正在参与常见的“MaxProfit”编程挑战.它基本上是这样的:
Given a zero-indexed array A consisting of N integers containing daily
prices of a stock share for a period of N consecutive days, returns
the maximum possible profit from one transaction during this period.
我对这个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(n2)时间内.
我做了一些关于这个主题的阅读,发现了一个非常相似的python解决方案. Python有一些非常方便的数组功能,允许使用a [s:e]语法分割数组,这与使用array_slice函数的PHP不同.我认为这一定是瓶颈所以我做了一些测试:
测试
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
题
>为什么PHP的array_slice()效率比Python低20倍?
>在PHP中是否有一个等效的方法来实现上述目标,从而有希望使我的maxProfit算法在O(N)时间内运行?编辑我意识到我上面的实现实际上并不是O(N),但我的问题仍然是关于切片数组的效率.