当前位置: 面试刷题>> 买卖股票的最佳时机 (经典算法题500道)


题目描述补充

买卖股票的最佳时机问题通常要求在一个数组中,数组的每个元素代表一天中某只股票的价格。假设你最多只能完成一次交易(即买入一次并卖出一次),设计一个算法来找到你所能获取的最大利润。

注意:你不能在买入股票前卖出股票,即你必须在买入股票之后才能卖出它。同时,你不能在同一天买入和卖出股票。

示例

给定一个数组,例如 [7,1,5,3,6,4],在这个例子中,在第2天(股票价格=1)买入,在第5天(股票价格=6)卖出,则最大利润为 6-1=5。但是,[7,6,4,3,1] 这样的数组中,由于价格一直在下跌,所以无法获得利润,这种情况下最大利润为 0。

PHP 示例代码

function maxProfit($prices) {
    $minPrice = PHP_INT_MAX;
    $maxProfit = 0;

    foreach ($prices as $price) {
        // 更新最低购买价格
        $minPrice = min($minPrice, $price);
        // 计算当前利润,并更新最大利润
        $maxProfit = max($maxProfit, $price - $minPrice);
    }

    return $maxProfit;
}

// 测试代码
$prices = [7, 1, 5, 3, 6, 4];
echo maxProfit($prices); // 输出 5

Python 示例代码

def maxProfit(prices):
    min_price = float('inf')
    max_profit = 0

    for price in prices:
        min_price = min(min_price, price)
        max_profit = max(max_profit, price - min_price)

    return max_profit

# 测试代码
prices = [7, 1, 5, 3, 6, 4]
print(maxProfit(prices))  # 输出 5

JavaScript 示例代码

function maxProfit(prices) {
    let minPrice = Infinity;
    let maxProfit = 0;

    for (let price of prices) {
        minPrice = Math.min(minPrice, price);
        maxProfit = Math.max(maxProfit, price - minPrice);
    }

    return maxProfit;
}

// 测试代码
let prices = [7, 1, 5, 3, 6, 4];
console.log(maxProfit(prices)); // 输出 5

码小课网站学习分享

码小课网站中提供了丰富的编程学习资源,包括但不限于算法、数据结构、编程语言基础等。你可以在这些课程中学习到更多关于解决买卖股票最佳时机问题的进阶方法和思路,以及其他面试中常见的算法题目解析。通过这些学习,你可以不断提升自己的编程能力和算法思维,为未来的职业发展打下坚实的基础。

推荐面试题