LeetCode 121. 买卖股票的最佳时机

121. 买卖股票的最佳时机

解题思路

参考代码

暴力解法

1
2
3
4
5
6
7
8
9
10
11
class 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;
}
}

一次遍历

分为两种情况:

  • 如果当前价格比之前的最低价格更低,则更新最低价格。
  • 如果当前价格比之前的最低价格更高,则计算当前利润,并更新最大利润
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class 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 121. 买卖股票的最佳时机
https://sowink.cn/2026/02/08/LeetCode-121-买卖股票的最佳时机/
作者
Xurx
发布于
2026年2月8日
许可协议