Skip to content

Instantly share code, notes, and snippets.

@fajarwz
Created July 14, 2022 14:39
Show Gist options
  • Save fajarwz/848b609c21bb72aaf80f5e13841fb351 to your computer and use it in GitHub Desktop.
Save fajarwz/848b609c21bb72aaf80f5e13841fb351 to your computer and use it in GitHub Desktop.
Max Profit
<?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