题目
解题思路
循环对比,第一天比第二天价格低就买入,第二天卖出以此类推
class Solution {
/**
* @param Integer[] $prices
* @return Integer
*/
function maxProfit($prices) {
$profit = 0;
for($i = 0; $i < count($prices); $i++)
{
if($prices[$i] < $prices[$i + 1])
{
$profit += $prices[$i + 1] - $prices[$i];
}
}
return $profit;
}
}
优化下
class Solution {
/**
* @param Integer[] $prices
* @return Integer
*/
function maxProfit($prices) {
$profit = 0;
for($i = 0; $i < count($prices); $i++)
{
$profit += $prices[$i + 1] > $prices[$i] ? $prices[$i + 1] - $prices[$i] : 0;
}
return $profit;
}
}