買股票的最佳時機:
PHP:
40ms。
class Solution {
/**
* @param Integer[] $prices
* @return Integer
*/
function maxProfit($prices) {
if(count($prices) == 0) return 0;
$maxProfit = -1;
$minPrice = PHP_INT_MAX;
for($i = 0;$i < count($prices);$i++){
$minPrice = min($prices[$i],$minPrice);
if($prices[$i] - $minPrice > $maxProfit){
$maxProfit = $prices[$i] - $minPrice;
}
}
return $maxProfit;
}
}