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.

Closed due to the fact that off-topic participants 0xdb , LFC , aleksandr barakin , Dmitry Kozlov , andreymal February 9 at 16:12 .

It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:

  • “Questions asking for help with debugging (“ why does this code not work? ”) Should include the desired behavior, a specific problem or error, and a minimum code for playing it right in the question . Questions without an explicit description of the problem are useless for other visitors. See How to create minimal, self-sufficient and reproducible example . " - 0xdb, LFC, aleksandr barakin, Dmitry Kozlov, andreymal
If the question can be reformulated according to the rules set out in the certificate , edit it .

  • Why not use the standard Math.max.apply(null, [10, 20, 40]) or Math.min.apply(null, [10, 20, 40]) ? - Ruslan Semenov
  • What is the output and what should be? - Enikeyschik February

2 answers 2

This is how it works and should look like. The first block if correct, and the second is not correct. It should be just the opposite with the sign > . And currMin is not needed at all.

 function getMaxProfit(arr) { var minIdx = 0; var maxIdx = 1; for (var i = 0; i < arr.length; i++) { if (arr[i] < arr[minIdx]) { minIdx = i; } if (arr[i] > arr[maxIdx]) { maxIdx = i; } } console.log(minIdx,maxIdx); var maxProfit = arr[maxIdx] - arr[minIdx]; return maxProfit; } var arr1 = [80, 80, 80, 80, 70]; console.log('max profit = ' + getMaxProfit(arr1)); 

    The desired result can be obtained with just one line of code:

     var maxProfit = Math.max(...arr1) - Math.min(...arr1)