Given an integer array, return the indices of all of its local maxima. The report says only that the task was to find a local maximum in an array; this version asks for every local maximum so that the answer is unique.
Function Signature
def local_maxima(nums: list[int]) -> list[int]:
Rules
-
Index
i
is a local maximum when
nums[i]
is strictly greater than each of its neighbours that exist:
nums[i - 1]
when
i > 0
, and
nums[i + 1]
when
i < len(nums) - 1
.
-
The first and last elements have one neighbour each. In a one-element array, the only element is a local maximum.
-
Equal neighbours do not count: in
[4, 4]
, neither element is a local maximum.
-
Return the indices in increasing order, or an empty list if there are none.
Constraints
-
1 <= len(nums) <= 10^5
-
-10^9 <= nums[i] <= 10^9
Examples
Example 1
Input: nums = [1, 3, 2, 4, 1]
Output: [1, 3]
3 is greater than 1 and 2, and 4 is greater than 2 and 1.
Example 2
Input: nums = [5, 5, 4, 6]
Output: [3]
The two 5s are equal neighbours, so neither is a local maximum. The last element, 6, has one neighbour, 4, and is greater than it.
Example 3
Input: nums = [7]
Output: [0]
A single element has no neighbours, so it is a local maximum.