为什么我的for循环没有从数组中返回最低值



所以我这里有这个代码,我想从这个数组[2,1,2,0,1]中接收的值是1,我知道如何让它跳过0,但由于某种原因,它接受2作为最低值,有人能向我解释为什么并找到处理它的方法吗?

let lowestP = 100000000000000000000000000
let highestP = 0
let startWorking = 0

for(let i = 0; i < prices.length;i++){

if(lowestP > prices[i] && prices[i] > 0){
lowestP = prices[i]
}if(highestP<prices[i]){
highestP = prices[i]
}
if(prices.indexOf(lowestP) > prices.indexOf(highestP)){
highestP = 0
continue

}
startWorking = highestP - lowestP

}return startWorking
};

我做了一些控制台日志记录,看起来[2,1,2,0,1]中的前2个是问题所在,但我没有找到解决方案

let prices = [2, 1, 2, 0, 1];
let lowestP = 999999999999999;
prices.forEach((price, index) =>
price > 0 && lowestP > price ? (lowestP = prices[index]) : null
);

您应该始终尝试使代码的结构具有自文档性。

例如,如果你首先想过滤你的数组,使某些值不存在,那么使用filter,如果你搜索最小值或最大值,那么使用相应的函数。

要将过滤后的数组传递给Math.min函数,可以使用排列语法(...(

let prices = [2, 1, 2, 0, 1]
prices = prices.filter(value => value > 0);
if (prices.length === 0) {
console.error('no prices larger then 0')
} else {
let lowestP = Math.min(...prices);
console.log(lowestP)
}

您应该保留最低和最高p的指数,price.indexOf(highestP(,对于第二个2,返回价格列表中第一个2的指数。

var maxProfit = function (prices)
{
let lowestP = 100000000000000000000000000
let highestP = 0
let startWorking = 0
for (let i = 0; i < prices.length; i++) {
if (lowestP > prices[i] && prices[i] > 0) {
lowestP = prices[i]
index_lowest = i
}
if (highestP < prices[i]) {
highestP = prices[i]
index_highest = i
}
if (index_lowest > index_highest) {
highestP = 0
continue
}
startWorking = highestP - lowestP
}
return startWorking
}

您的代码非常好(您在查询中显示的内容(。无论如何,我认为您需要显示更多的代码片段来区分问题。如何处理数组中的0值?可能存在一些问题。但只是为了参考附加一段代码从数组中查找最小值。

public static int getMaxValue(int[] numbers){
int maxValue = numbers[0];
for(int i=1;i < numbers.length;i++){
if(numbers[i] > maxValue){
maxValue = numbers[i];
}
}
return maxValue;
}
public static int getMinValue(int[] numbers){
int minValue = numbers[0];
for(int i=1;i<numbers.length;i++){
if(numbers[i] < minValue){
minValue = numbers[i];
}
}
return minValue;
}

最新更新