原题链接:
https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/
完成情况:
解题思路:
这段代码的目的是解决LeetCode上的第121题“买卖股票的最佳时机”。题目要求你设计一个算法来计算你所能获取的最大利润。你只能选择某一天买入这只股票,并选择在未来的某一个不同的日子卖出该股票。
代码的核心思想是找到一个买入的最小值,然后在后续的价格中找到最大的利润值。具体的步骤如下:
-
初始化变量:
int minPrice = Integer.MAX_VALUE; int maxProfit = 0;
minPrice
初始化为整数的最大值,用于存储遍历过程中的最低股票价格。maxProfit
初始化为0,用于存储遍历过程中的最大利润。
-
遍历价格数组:
for (int i = 0; i < prices.length; i++) { if (prices[i] < minPrice) { minPrice = prices[i]; } else if (prices[i] - minPrice > maxProfit) { maxProfit = prices[i] - minPrice; } }
- 循环遍历每一天的股票价格。
- 如果当前价格
prices[i]
小于minPrice
,更新minPrice
为当前价格。这一步确保我们找到最低的买入价格。 - 否则,计算当前价格
prices[i]
和minPrice
的差值(即当前可能的利润),如果这个利润大于maxProfit
,则更新maxProfit
。
-
返回结果:
return maxProfit;
- 遍历结束后,返回
maxProfit
,即能获得的最大利润。
- 遍历结束后,返回
总结:这段代码的时间复杂度是 O(n),因为它只需要遍历一次价格数组。通过在遍历的过程中不断更新最低买入价格和最大利润,它能够在一次遍历中找到最佳的买卖时机。
参考代码:
_121买卖股票的最佳时机
package leetcode板块;
public class _121买卖股票的最佳时机 {
/**
*
* @param prices
* @return
*/
public int maxProfit(int[] prices) {
// 你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
// 某一天买入,另一天卖出
// 找出最小值,每一个值去和最小值做差
int minPrice = Integer.MAX_VALUE;
int maxProfit = 0;
for (int i = 0;i<prices.length;i++){
if (prices[i] < minPrice){
minPrice = prices[i];
} else if (prices[i] - minPrice > maxProfit) {
maxProfit = prices[i] - minPrice;
}
}
return maxProfit;
}
}