Pergunta de entrevista da empresa webiks

given an array of integers, without reordering, determine the maximum difference between any element and prior smaller element. If there is never a lower prior element, return -1. example arr = [5,3,6,7,4] there are no earlier elements than arr[0]. there is no earlier reading with a value lower than arr[1]. there are two lower earlier readings with a value lower than arr[2]=6: • arr[2] - arr[1] = 6 - 3 = 3 • arr[2] - arr[0] = 6 - 5 = 1 there are three lower earlier readings with a lower value than arr[3]=7: • arr[3] - arr[2] = 7 - 6 = 1 • arr[3] - arr[1] = 7 - 3 =4 • arr[3] - arr[0] = 7 - 5 =2 there is one lower earlier reading with a lower value than arr[4]=4: • arr[4] - arr[1] = 4 - 3 = 1 the maximum trailing record is arr[3] - arr[1] = 4

Resposta da entrevista

Sigiloso

5 de jan. de 2024

function maxTrailing(arr) { if (arr.length < 2) { return -1; // There must be at least two elements for a valid comparison } let maxDifference = -1; for (let i = 1; i < arr.length; i++) { for (let j = i - 1; j >= 0; j--) { if (arr[i] > arr[j]) { const difference = arr[i] - arr[j]; maxDifference = Math.max(maxDifference, difference); } } } return maxDifference; }