![]() |
"踏上LeetCode解題之路,順手紀錄一下PHP練功的過程囉。這是第十二篇~~" |
Best Time to Buy and Sell Stock - LeetCode
思考過程
待補上
結果✅
// 相減 找出利潤最大值 class Solution { /** * @param Integer[] $prices * @return Integer */ function maxProfit(array $prices) { $min= $prices[0]; $maxProfit = 0; for ($i = 1; $i < count($prices); $i++) { if ($min > $prices[$i]) { $min = $prices[$i]; } if ($maxProfit < ($prices[$i] - $min)) { $maxProfit = $prices[$i] - $min; } } return $maxProfit; }
/** * @param array $prices Stock prices array for each day. * @return int the max profit possible in the market. */ function maxProfit(array $prices) { $maxProfit = 0; for ($i = 0; $i < count($prices); $i++) { for($j = $i +1; $j < count($prices); $j++) { if ($prices[$i] >= $prices[$j]) { continue; } $diff = $prices[$j] - $prices[$i]; $maxProfit = $diff > $maxProfit ? $diff : $maxProfit; } } return $maxProfit; }
if ($buy > $maxProfit){ $maxProfit = $buy; }