LeetCode 121. 买卖股票的最佳时机 121. 买卖股票的最佳时机解题思路 参考代码暴力解法1234567891011class Solution { public int maxProfit(int[] prices) { int maxProfit = 0; for(int i = 0; i < prices.length; i ++) { for(int j = i + 1; j < prices.length; j ++) { maxProfit = Math.max(maxProfit, prices[j] - prices[i]); } } return maxProfit; }} 一次遍历分为两种情况: 如果当前价格比之前的最低价格更低,则更新最低价格。 如果当前价格比之前的最低价格更高,则计算当前利润,并更新最大利润 123456789101112131415class Solution { public int maxProfit(int[] prices) { int minPrice = Integer.MAX_VALUE; int maxProfit = 0; for(int price : prices) { if(price < minPrice) { minPrice = price; // 更新最低的购入价格 } else if (price - minPrice > maxProfit) { maxProfit = price - minPrice; // 更新利润 } } return maxProfit; }} LeetCode LeetCode 121. 买卖股票的最佳时机 https://sowink.cn/2026/02/08/LeetCode-121-买卖股票的最佳时机/ 作者 Xurx 发布于 2026年2月8日 许可协议 LeetCode 118. 杨辉三角 上一篇 LeetCode 124. 二叉树中的最大路径和 下一篇 Please enable JavaScript to view the comments