如何修改下面一段代码使其输出结果舍弃“第6天买入,第5天卖出”这种情况,可以出现“第1天买入,第1天卖出“这种情况,来保证不亏损
package com.youkeda.p2.exam;
public class Horse {
public static void main(String[] args) {
int[] prices = {5, 3, 7, 10, 13, 2};
int[] result = profit(prices);
System.out.println("第 " + (result[0] + 1) + " 天买入,第 " + (result[1] + 1) + " 天卖出,盈利 " + result[2]);
}
public static int[] profit(int[] prices){
if (prices == null || prices.length == 0){
return new int[] {0,0,0};
}
int minPrice = prices[0];
int maxPrice = 0;
int buyDay = 0;
int sellDay = 0;
for (int i = 1; i < prices.length;i++){
if (prices[i] < minPrice){
minPrice = prices[i];
buyDay = i;
}
else {
int pofit = prices[i] - minPrice;
if (pofit > maxPrice) {
maxPrice = pofit;
sellDay = i;
}
}
}
return new int[] {buyDay,sellDay,maxPrice};
}
}
当当前日期价格小于最低售价的那个if修改下即可。
修改如下:
public class Horse {
public static void main(String[] args) {
int[] prices = {5, 3, 7, 10, 13, 2};
// int[] prices = {0, 0,0, 0, 0, 1};
int[] result = profit(prices);
System.out.println("第 " + (result[0] + 1) + " 天买入,第 " + (result[1] + 1) + " 天卖出,盈利 " + result[2]);
}
public static int[] profit(int[] prices){
if (prices == null || prices.length == 0){
return new int[] {0,0,0};
}
int minPrice = prices[0];
int maxPrice = 0;
int buyDay = 0;
int sellDay = 0;
for (int i = 0; i < prices.length;i++){
// 当此日价格小于最低价格,则将价格赋值给最低价格
// 然后计算以后日期内,那天卖出收益最高
if (prices[i] < minPrice){
minPrice = prices[i];
// 判断此日之后,哪天卖出收益最高
for (int j=i+1;j<prices.length;j++) {
// 当此日卖出高于以前的最高收益
// 则将前一步记录的日期为购买日期
// 此日设置为卖出日期
// 此日价格减去上一步日期价格为最高售价
if((prices[j]-minPrice)>maxPrice) {
buyDay=i;
maxPrice = prices[j]-minPrice;
sellDay = j;
}
}
} else {
int pofit = prices[i] - minPrice;
if (pofit > maxPrice) {
maxPrice = pofit;
sellDay = i;
}
}
}
return new int[] {buyDay,sellDay,maxPrice};
}
}
1.先创建一个新的数组,长度为原来的 -1
2.把 其他的元素复制到新的数组中
3.把新数组的首地址赋值给原来的变量
4.垃圾回收会慢慢回收在堆内存中的数组
我可以帮你解决这个问题。根据你提供的参考资料,我看到你想要修改代码以避免亏损情况的出现,并且希望结果中包括“第1天买入,第1天卖出”的情况。下面是我给出的解决方案:
public class Solution {
public static void main(String[] args) {
int[] prices = {5, 10, 20, 8, 25, 15, 30}; // 假设这是每天的股票价格
int minPrice = Integer.MAX_VALUE; // 初始化最低价格为最大值
int maxProfit = 0; // 初始化最大收益为0
int buyDay = 0; // 买入的天数
int sellDay = 0; // 卖出的天数
for (int i = 0; i < prices.length; i++) {
if (prices[i] < minPrice) {
minPrice = prices[i];
buyDay = i + 1; // 买入的天数为数组下标+1
sellDay = i + 1; // 卖出的天数也为数组下标+1
} else if (prices[i] > minPrice && prices[i] - minPrice > maxProfit) {
maxProfit = prices[i] - minPrice;
sellDay = i + 1; // 卖出的天数为数组下标+1
}
}
// 输出买卖情况
System.out.println("第" + buyDay + "天买入,第" + sellDay + "天卖出");
}
}
在这个解决方案中,我使用了一个for循环来遍历股票价格的数组。我使用两个变量minPrice
和maxProfit
来记录最低价格和最大收益。在每一次循环中,我检查当前价格是否比之前的最低价格更低,如果是,则更新最低价格,并更新买入和卖出的天数。如果当前价格比最低价格高,并且卖出后的收益大于之前的最大收益,则更新最大收益和卖出的天数。最后,我输出买卖的情况,其中买入和卖出的天数分别为buyDay
和sellDay
。
这样修改后的代码可以避免亏损情况的出现,并且会输出包括“第1天买入,第1天卖出”的情况。希望这个解决方案对你有帮助!如果你有任何其他问题,请随时提问。