分裂php,PHP的array_slice与Python的分裂数组

一些背景

我正在参与常见的“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),但我的问题仍然是关于切片数组的效率.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值