-3

I need to create a function which finds the two numbers with the largest difference between them and returns their indices as an array of two elements - [ lowest, biggest ].

Notice: the bigger number must be to the right from lowest. If we have no difference between the numbers, the function must return [].

function getProfit(arr) {
    let result = [];
    let sortedArr = arr.sort();
    let min = sortedArr.indexOf(Math.min(...sortedArr));
    let max = sortedArr.indexOf(Math.max(...sortedArr));
    if(max > min) {
        result.push(min);
        result.push(max);
        return result;
    } else {
        return [];
    }

}

console.log(getProfit([13, 6, 3, 4, 10, 2, 3], [2, 4]));
lejlun
  • 4,140
  • 2
  • 15
  • 31

1 Answers1

2

You need to iterate through the list with two pointers (indexes) left and right as described below: you will accomplish your solution with time complexity of O(n).

function getProfit(arr) {
    let result = [0,0];
    for(let l=0,r=0; l<arr.length-1 && r<arr.length-1;r++){
        if(arr[l] > arr[r]){
            l++;
        }else if(arr[r]-arr[l]> arr[result[1]]-arr[result[0]]){
            result[0] = l;
            result[1] = r;
        }
    }
    return (result[1] === 0) ? [] : result;
}

console.log(getProfit([13, 6, 3, 4, 10, 2, 3]));
Daniel
  • 1,895
  • 9
  • 20