Say you have an array for which the i th element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
假设你有一个数组,其中第i个元素是某只股票在第i天的价格。
设计一个算法来求最大的利润。你最多可以进行两次交易。
注意:
你不能同时进行多个交易(即,你必须在再次购买之前出售之前买的股票)。
思路:就是求两次差值和最大,确定每个位置分割的差值的最大,然后再把整体的最大差值和求出来。
<?php
function maxProfit($arrPrice) {
$num = count($arrPrice);
//先算i之前最大的价格差
$arrPro1 = array();
$minPrice = $arrPrice[0];
for ($i = 1; $i < $num; $i ++) {
$arrPro1[$i] = max($arrPro1[$i - 1], $arrPrice[$i] - $minPrice);
if ($minPrice > $arrPrice[$i]) {
$minPrice = $arrPrice[$i];
}
}
print json_encode($arrPro1);
//再算i之后的最大价格差
$arrPro2 = array();
$maxPrice = $arrPrice[$num -1];
for ($i = $num - 2; $i > 0; $i --) {
$arrPro2[$i] = max($arrPro2[$i + 1], $maxPrice - $arrPrice[$i]);
if ($maxPrice < $arrPrice[$i]) {
$maxPrice = $arrPrice[$i];
}
}
$maxProfit = 0;
for ($i = 1; $i < $num -1; $i ++) {
$maxProfit = max($maxProfit, $arrPro1[$i] + $arrPro2[$i]);
}
return $maxProfit;
}
$arrPrice = [1,2,3,4,5,6,7];
$ret = maxProfit($arrPrice);
print $ret;