假设你有一个数组,其中第i个元素是某只股票在第i天的价格。
如果你最多只能完成一笔交易(即买一股和卖一股股票),设计一个算法来求最大利润。
Say you have an array for which the i th element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit
<?php
function maxProfit($arrPrice) {
$num = count($arrPrice);
//不能满足基本的两次买卖
if ($num < 2) {
return 0;
}
$min = $arrPrice[0];
$maxProfit = 0;
for ($i = 1; $i < $num; $i ++) {
$profit = $arrPrice[$i] - $min;
$maxProfit = $maxProfit < $profit ? $profit : $maxProfit;
if ($min > $arrPrice[$i]) {
$min = $arrPrice[$i];
}
}
return $maxProfit;
}
$arrPrice = [1,2,3,4,5,6,7];
$arrPrice = array(1,2,3,4,5,4,4);
$ret = maxProfit($arrPrice);
print $ret;