Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, 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);
//不能满足基本的两次买卖
if ($num < 2) {
return 0;
}
//先算i之前最大的价格差
$min = $arrPrice[0];
$isAdd = 0;
$isSub = 0;
$maxProfit = 0;
for ($idx = 1; $idx < $num; $idx ++) {
if ($arrPrice[$idx] > $arrPrice[$idx - 1] ) {
//递减的结束位置
if ($isSub == 1) {
$min = $arrPrice[$idx - 1];
}
//单增的情况
if ($idx == $num - 1) {
$maxProfit += $arrPrice[$idx] - $min;
}
$isAdd = 1;//标志递增
$isSub = 0;//标记递减
}
if ($arrPrice[$idx] < $arrPrice[$idx - 1]) {
//递增结束的位置
if ($isAdd == 1) {
$maxProfit += $arrPrice[$idx - 1] - $min;
}
$isAdd = 0;//标志递增
$isSub = 1;//标记递减
}
print $idx. ' ' . $maxProfit . ' ' . $arrPrice[$idx] . "\n";
}
return $maxProfit;
}
$arrPrice = [1,2,3,4,5,6,7];
//$arrPrice = array(1,2,3,4,5,4,7);
$ret = maxProfit($arrPrice);
print $ret;
其实上面的比较麻烦,虽然题目限制了一天不能同时交易,但是我们可以直接把所有递增的收益求出来,就不用记录哪里到哪里是递增了。
<?php
function maxProfit($arrPrice) {
$num = count($arrPrice);
$maxProfit = 0;
for ($i = 1; $i <$num; $i ++) {
if ($arrPrice[$i] > $arrPrice[$i - 1]) {
$maxProfit += $arrPrice[$i] - $arrPrice[$i - 1];
}
}
return $maxProfit;
}
$arrPrice = [1,2,3,4,5,6,7,1,2,3];
//$arrPrice = array(1,2,3,4,5,4,7);
$ret = maxProfit($arrPrice);
print $ret;