Say you have an array for which the ith 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.
Input: [7, 1, 5, 3, 6, 4]
Output: 5
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be
larger than buying price)
也就是说第一天的价格是买入价格是7 , 第二天买入价格是1
也就是低价买入,高价卖出,求收益最大化
// 获取最大收益
/**
* we need to find max(prices[j] - prices[i]), for every i and j such that j > i.
*/
function maxProfit($prices) {
// 没有任何交易
if (count($prices) == 0) {
return 0;
}
// 初始最小价格
$minPrice = $prices[0];
// 初始利润为0
$maxProfit = 0;
for ($i = 1; $i < count($prices); $i++) {
if ($prices[$i] < $minPrice)
$minPrice = $prices[$i];
else if ($prices[$i] - $minPrice > $maxProfit)
$maxProfit = $prices[$i] - $minPrice;
}
return $maxProfit;
}
echo maxProfit([7, 1, 5, 3, 6, 4]);
echo maxProfit([7, 6, 4, 3, 1]);
// 时间复杂度: O(n)
// 空间复杂度:O(1)
// 方法二
function maxProfit_1($prices) {
$maxProfit = 0;
$len = count($prices);
for ($i = 0; $i < $len - 1; $i++) {
for ($j = $i + 1; $j < $len; $j++) {
$profit = $prices[$j] - $prices[$i];
$maxProfit = $maxProfit > $profit ? $maxProfit : $profit;
}
}
return $maxProfit;
}
echo maxProfit_1([7, 1, 5, 3, 6, 4]);
// 时间复杂度: O(n²)
// 空间复杂度:O(1)