PHP's array_slice vs Python's splitting arrays -


some background

i having go @ common "maxprofit" programming challenge. goes this:

given zero-indexed array consisting of n integers containing daily prices of stock share period of n consecutive days, returns maximum possible profit 1 transaction during period.

i quite pleased php algorithm came up, having avoided naive brute-force attempt:

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; } 

however, having tested solution seems perform badly performance-wise, perhaps in o(n2) time.

i did bit of reading around subject , discovered similar python solution. python has quite handy array abilities allow splitting array a[s : e] syntax, unlike in php used array_slice function. decided must bottleneck did tests:

tests

php array_slice()

$n = 10000;     $a = range(0,$n);  $start = microtime(1); foreach ($a $key => $elem) {     $subarray = array_slice($a, $key); } $end = microtime(1);  echo sprintf("time taken: %sms", round(1000 * ($end - $start), 4)) . php_eol; 

results:

$ php phpslice.php time taken: 4473.9199ms time taken: 4474.633ms time taken: 4499.434ms 

python a[s : e]

import time  n = 10000 = range(0, n)  start = time.time() key, elem in enumerate(a):     subarray = a[key : ] end = time.time()  print "time taken: {0}ms".format(round(1000 * (end - start), 4)) 

results:

$ python pyslice.py  time taken: 213.202ms time taken: 212.198ms time taken: 215.7381ms time taken: 213.8121ms 

question

  1. why php's array_slice() around 20x less efficient python?
  2. is there equivalently efficient method in php achieves above , makes maxprofit algorithm run in o(n) time? edit realise implementation above not o(n), question still stands regarding efficiency of slicing arrays.

  1. i don't know, php's arrays messed hybrid monsters, maybe that's why. python's lists lists, not @ same time dictionaries, might simpler/faster because of that.
  2. yes, actual o(n) solution. solution isn't slow because php's slicing apparently slow, it's slow because have o(n^2) algorithm. walk on array once, keep track of minimum price found far, , check current price. not max on half array in every single loop iteration.

Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -