Created
July 14, 2022 14:39
-
-
Save fajarwz/848b609c21bb72aaf80f5e13841fb351 to your computer and use it in GitHub Desktop.
Max Profit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// https://coderbyte.com/algorithm/stock-maximum-profit | |
function StockPicker($arr) { | |
$buyPrice = 0; | |
$sellPrice = 0; | |
$maxProfit = -1; | |
$changeBuyIndex = true; | |
for($i = 0; $i < count($arr) - 1; $i++) { | |
if($changeBuyIndex) { | |
$buyPrice = $arr[$i]; | |
} | |
// echo "Buy price: " . $buyPrice . ' '; | |
$sellPrice = $arr[$i+1]; | |
// echo "Sell price: " . $sellPrice . ' '; | |
if($buyPrice < $sellPrice) { | |
$changeBuyIndex = false; | |
$currentProfit = $sellPrice - $buyPrice; | |
if($maxProfit < $currentProfit) | |
$maxProfit = $currentProfit; | |
} else { | |
$changeBuyIndex = true; | |
} | |
// echo "Max profit: " . $maxProfit; | |
// echo "\n"; | |
} | |
return $maxProfit; | |
} | |
echo StockPicker([44, 30, 24, 32, 40, 20, 40, 38, 15]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment