题目
选自力扣
买卖股票的最佳时机
给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。
示例 1:
输入:[7,1,5,3,6,4] 输出:5 解释:在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,
最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。示例 2:
输入:prices = [7,6,4,3,1] 输出:0 解释:在这种情况下, 没有交易完成, 所以最大利润为 0。
提示:
1
<
=
p
r
i
c
e
s
.
l
e
n
g
t
h
<
=
1
0
5
1 <= prices.length <= 10^5
1<=prices.length<=105
0
<
=
p
r
i
c
e
s
[
i
]
<
=
1
0
4
0 <= prices[i] <= 10^4
0<=prices[i]<=104
这个问题可以通过一次遍历来解决。我们需要跟踪两个重要的变量:最低价格(minPrice
)和最大利润(maxProfit
)。随着我们遍历数组,我们将更新这两个变量。
- 初始化
minPrice
为正无穷大(或者数组的第一个元素),maxProfit
为 0。 - 遍历数组中的每个价格:
- 如果当前价格比
minPrice
更低,则更新minPrice
。 - 否则,计算当前价格与
minPrice
的差值,并与maxProfit
比较,如果更大,则更新maxProfit
。
- 如果当前价格比
- 完成遍历后,
maxProfit
将包含最大可能的利润。
下面是这个问题的 Java 代码实现:
public class StockProfitCalculator { // 定义类StockProfitCalculator
public static int maxProfit(int[] prices) { // 定义静态方法maxProfit,参数为整型数组prices,返回值为整型
if (prices == null || prices.length < 2) { // 检查prices是否为空或长度小于2,如果是则返回0,因为至少需要两天的价格数据才能计算利润
return 0;
}
int minPrice = Integer.MAX_VALUE; // 初始化最小价格为整型最大值,确保任何实际价格都会小于这个值
int maxProfit = 0; // 初始化最大利润为0
for (int price : prices) { // 遍历prices数组中的每个价格
if (price < minPrice) { // 如果当前价格低于已知的最小价格
minPrice = price; // 更新最小价格为当前价格
} else { // 否则
maxProfit = Math.max(maxProfit, price - minPrice); // 计算当前价格和最小价格的差值,如果大于当前最大利润,则更新最大利润
}
}
return maxProfit; // 返回计算得到的最大利润
}
public static void main(String[] args) { // 主函数,程序的入口
int[] example1 = {7, 1, 5, 3, 6, 4}; // 定义一个示例数组example1
int[] example2 = {7, 6, 4, 3, 1}; // 定义另一个示例数组example2
System.out.println("Example 1: Max Profit = " + maxProfit(example1)); // 输出example1的最大利润,预期结果为5
System.out.println("Example 2: Max Profit = " + maxProfit(example2)); // 输出example2的最大利润,预期结果为0,因为价格持续下跌,无法获得正利润
}
}
测试代码
为了验证上述函数的正确性,我们可以编写一些测试代码:
public static void main(String[] args) {
int[] example1 = {7, 1, 5, 3, 6, 4};
int[] example2 = {7, 6, 4, 3, 1};
System.out.println("Example 1: Max Profit = " + maxProfit(example1)); // Should print 5
System.out.println("Example 2: Max Profit = " + maxProfit(example2)); // Should print 0
}
这样,我们就有了一个简单且高效的解决方案来计算给定价格数组中的最大利润。
如果我知道以后每天的股票价格,我一定用这个算法来买.