一次交易:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/
<?php
function maxProfit($prices)
{
$count = count($prices);
if ($count <= 1){
return 0;
}
$minPos = 0;
$maxPrice = 0;
$start = 0;
$end = 0;
for ($i = 0; $i < $count; $i++){
if ( $prices[$i] < $prices[$minPos] ){
$minPos = $i;
}else{
$diff = $prices[$i] - $prices[$minPos];
if ($maxPrice < $diff){
$start = $minPos;
$end = $i;
$maxPrice = $diff;
}
}
}
return $maxPrice;
}
$prices = [7,1,5,3,6,4];
echo maxProfit($prices);
不限次交易:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/
<?php
function maxProfit($prices)
{
$count = count($prices);
if ($count <= 1){
return 0;
}
$price = 0;
$diff = 0;
$i = 0;
$j = 1;
$min_pos = 0;
while ($j < $count){
if ( $prices[$j] < $prices[$i] ){
$min_pos = $j;
if ($diff > 0){
$price += $diff;
$diff = 0;
}
}else{
$tmp_diff = $prices[$j] - $prices[$min_pos];
if ($tmp_diff > $diff){
$diff = $tmp_diff;
}
}
$i++;
$j++;
}
//处理只涨不跌
if ($diff > 0){
$price += $diff;
}
return $price;
}
$prices = [7, 1, 5, 3, 6, 4, 5];
echo maxProfit($prices);