Find the index of any peak element in a given array. A peak element is an element that is strictly greater than both of its immediate neighbors. The first and last elements of the array are considered to be adjacent to negative infinity. If multiple peaks exist, return the index of any one of them.
Go through the list one by one, starting from the second number and ending before the last number. If a number is greater than both the number before it and the number after it, it's considered a "peak." If a peak is found, add it to a separate list. After checking all numbers, if any peaks were found, return the first peak in the list of saved peaks. Otherwise, return -1 to indicate that no peaks were found.
ls = [1, 3, 4, 5, 8, 7, 3, 6] output = [] for i in range(len(ls)): item = ls[i] before = float('-inf') if i - 1 < 0 else ls[i - 1] after = float('-inf') if i + 1 >= len(ls) else ls[i + 1] if item > before and item > after: output.append(i) print(output[0] if len(output) > 0 else -1)
const list = [1, 3, 4, 5, 8, 7, 3, 6]; const output = []; for (let i = 0; i < list.length; i++) { const before = (i == 0) ? -Infinity : list[i - 1]; const after = (i == list.length - 1) ? -Infinity : list[i + 1]; const item = list[i]; if (item > before && item > after) { output.push(i); } } console.log(output.length > 0 ? output[0] : -1);