There is such a code:
function getMaxProfit(arr) { var minIdx = 0; var maxIdx = 1; var currMin = 0; var maxProfit = 0; if (arr.length < 2) { throw new Error("Needs more data"); } for (var i = 0; i < arr.length; i++) { console.log('i' + i); // new min. if (arr[i] < arr[currMin]) { console.log('i opa' + i); currMin = i; } console.log(arr[maxIdx], arr[minIdx]) console.log(arr[i], arr[currMin]) // new best profit if (arr[maxIdx] - arr[minIdx] < arr[i] - arr[currMin]) { console.log('i vita' + i); maxIdx = i; minIdx = currMin; } } console.log(maxIdx); console.log(minIdx); maxProfit = arr[maxIdx] - arr[minIdx]; return maxProfit; } var arr1 = [80, 80, 80, 80, 70]; var arr2 = [1]; //for test console.log('max profit = ' + getMaxProfit(arr1)); This function is a function of finding the maximum benefit.
For example, with input data 100,100,100,90,100
The benefit will be max - min, that is, 100 - 90 = 10.
The problem is that the algorithm does not take into account the last element, if the element has a minimum value, and the first element, if it has a maximum value. And I myself do not see the reason. Please tell me what is my mistake.
Math.max.apply(null, [10, 20, 40])orMath.min.apply(null, [10, 20, 40])? - Ruslan Semenov