针对下面代码进行修改呢public class Horse { public static void main(String[] args) { int[] prices = {7,1,8,11,19,3,6}; System.out.println("第 " + prices[0] + " 天买入,第 " + (prices[1] + 1) + " 天卖出,盈利 " + prices[2]); } public static void profit(int[] prices){ if (prices == null || prices.length == 0){ 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]; } } } }
时间: 2024-02-27 22:55:45 浏览: 74
在原代码中,`profit` 方法中计算了最大利润,但并没有将结果返回或输出。为了得到最大利润的结果,我们需要将 `maxProfit` 从 `profit` 方法中返回,并在 `main` 方法中输出结果。
修改后的代码如下:
```java
public class Horse {
public static void main(String[] args) {
int[] prices = {7,1,8,11,19,3,6};
int[] result = profit(prices);
System.out.println("第 " + result[0] + " 天买入,第 " + (result[1] + 1) + " 天卖出,盈利 " + result[2]);
}
public static int[] profit(int[] prices){
if (prices == null || prices.length == 0){
return new int[]{0, 0, 0};
}
int maxProfit = 0;
int buyPrice = prices[0];
int sellPrice = prices[0];
int buyDay = 0;
int sellDay = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] < buyPrice) {
buyPrice = prices[i];
buyDay = i;
} else if (prices[i] - buyPrice > maxProfit) {
maxProfit = prices[i] - buyPrice;
sellPrice = prices[i];
sellDay = i;
}
}
return new int[]{buyDay, sellDay, maxProfit};
}
}
```
在 `profit` 方法中添加了 `buyDay` 和 `sellDay` 变量,分别表示买入和卖出的日期。在找到最大利润时,同时更新 `sellDay` 的值。将最大利润、买入日期和卖出日期作为数组返回,在 `main` 方法中输出对应的结果。
阅读全文