PHP longest increasing subsequence -


so there answers on here apply c trying in php, , in particular way.

i have array of numbers :

7, 2, 6, 3, 10

i want find longest increasing subsequence happens first in order given. example in case want result be:

2, 6, 10

and not 2, 3, 10.

what best way accomplish ?

okay, here's solution question yielding answer expect. basically, every element found start list , add items when greater last item in list far.

$input = array(7,2,6,3,10); $trial = array();  echo "input: "; print_r($input); echo "<br><br>\n";  foreach ($input $key => $value) {   // create new trial each starting point   // ------------------------------------------   $trial[$key][0] = $value;   echo "trial $key started<br>\n";    // process prior trials   // ------------------------   ($i = $key-1; $i >= 0; $i--)   {     echo "looking @ trial $i ";     $last = count($trial[$i]) - 1;     $lastval = $trial[$i][$last];     if ( $value > $lastval )     {       $trial[$i][] = $value;       echo "** added $value";     }     echo "<br>\n";   }   echo "<br>\n"; }  // find first longest trial // ------------------------ $longest = 0; foreach ($trial $key => $list) {   if ( count($list) > count($trial[$longest]) )     $longest = $key; }  echo "all trials:<br>\n"; print_r($trial); echo "<br><br>\n";  echo "first longest sequence:<br>\n"; print_r($trial[$longest]); 

there of course things done differently if had large data sets. said, here "debug" output showing in action:

input: array ( [0] => 7 [1] => 2 [2] => 6 [3] => 3 [4] => 10 )   trial 0 started  trial 1 started ... looking @ trial 0   trial 2 started ... looking @ trial 1 ** added 6 ... looking @ trial 0   trial 3 started ... looking @ trial 2  ... looking @ trial 1  ... looking @ trial 0   trial 4 started ... looking @ trial 3 ** added 10 ... looking @ trial 2 ** added 10 ... looking @ trial 1 ** added 10 ... looking @ trial 0 ** added 10  trials: array (    [0] => array ( [0] => 7 [1] => 10 )    [1] => array ( [0] => 2 [1] => 6 [2] => 10 )    [2] => array ( [0] => 6 [1] => 10 )    [3] => array ( [0] => 3 [1] => 10 )    [4] => array ( [0] => 10 )  )   first longest sequence: array ( [0] => 2 [1] => 6 [2] => 10 ) 

Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -