给定一个数组 prices
,它的第 i
个元素 prices[i]
表示一支给定股票第 i
天的价格。
你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0
。
public class MaxProfit {
public static void main(String[] args) {
int[] prices = {7, 1, 5, 3, 6, 4}; // 示例数组
int maxProfit = maxProfit(prices);
System.out.println("可以获取的最大利润: " + maxProfit);
}
public static int maxProfit(int[] prices) {
// 如果数组为空或长度为1,则没有交易可进行
if (prices == null || prices.length < 2) {
return 0;
}
int minPrice = prices[0]; // 最低价格初始化为第一天的价格
int maxProfit = 0; // 最大利润初始化为0
for (int i = 1; i < prices.length; i++) {
// 更新最低价格
if (prices[i] < minPrice) {
minPrice = prices[i];
} else {
// 计算当前利润
int currentProfit = prices[i] - minPrice;
// 更新最大利润
maxProfit = Math.max(maxProfit, currentProfit);
}
}
return maxProfit;
}
}
代码解释:
-
初始化: 我们设置一个变量
minPrice
来存储遇到的最低价格,并初始化为数组的第一个元素。同时,也初始化一个变量maxProfit
为 0,用来记录能获得的最大利润。 -
遍历价格数组: 从第二天开始(索引 1),依次检查每一天的价格:
- 如果当前价格小于
minPrice
,那么更新minPrice
为当前价格。 - 否则,计算当前的利润(当前价格 -
minPrice
)并查看是否比目前的maxProfit
更高。如果是,则更新maxProfit
。
- 如果当前价格小于
-
返回结果: 遍历结束后,
maxProfit
就是能够获得的最大利润。如果没有利润可得,maxProfit
会返回 0。
时间复杂度:
这个算法的时间复杂度是 O(n),其中 n 是数组的长度,因为我们只需要遍历价格数组一次。空间复杂度是 O(1),因为我们只用了一些额外的变量。