上述代码的方法maxProfit如果用void而不是int[]该如何改进
时间: 2024-01-12 15:02:21 浏览: 23
如果将 `maxProfit` 方法的返回类型从 `int[]` 改为 `void`,则可以通过将最大利润、买入和卖出价格作为参数传递给方法来实现相同的功能。
修改后的方法如下所示:
```java
public static void maxProfit(int[] prices) {
if (prices == null || prices.length < 2) {
return;
}
int maxProfit = 0;
int buyPrice = prices[0];
int sellPrice = prices[0];
for (int i = 1; i < prices.length; i++) {
if (prices[i] < buyPrice) {
buyPrice = prices[i];
} else if (prices[i] - buyPrice > maxProfit) {
maxProfit = prices[i] - buyPrice;
sellPrice = prices[i];
}
}
System.out.println("Max Profit: " + maxProfit);
System.out.println("Buy Price: " + buyPrice);
System.out.println("Sell Price: " + sellPrice);
}
```
在这个版本中,maxProfit方法会输出最大利润,买入价格和卖出价格。这些值可以通过调用该方法时传递的参数来计算。因此,如果要使用该方法,需要将股票价格数组作为参数传递给该方法。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)