To solve this problem, we need to find the index of the first occurrence of the maximum element in an array of integers. If there are multiple instances of the maximum element, we return the smallest index among them.
Approach
The approach to solve this problem involves two main steps:
- Find the Maximum Value: First, we determine the maximum value present in the array using the built-in
max()function (or by iterating through the array if needed, butmax()is efficient and concise). - Locate the First Occurrence: Next, we iterate through the array from the start (index 0) to find the first element that matches the maximum value. The index of this element is our answer, as we stop immediately upon finding the first match.
Solution Code
def find_first_max_index(arr):
max_val = max(arr)
for idx, num in enumerate(arr):
if num == max_val:
return idx
Explanation
- Finding the Maximum: The
max(arr)function efficiently computes the highest value in the array in O(n) time, where n is the length of the array. - First Occurrence Check: Using
enumerate(arr)allows us to iterate over both the index and value of each element in the array. As soon as we encounter an element equal to the maximum value, we return its index—this ensures we get the first occurrence since we are iterating from left to right.
Key Notes
- Time Complexity: O(n) (we traverse the array once to find the maximum, then again up to the first occurrence of the maximum—total O(n)).
- Space Complexity: O(1) (we only use a few variables to store the maximum value and current index).
- Edge Cases: Handles all edge cases like empty arrays (though the problem assumes non-empty input), single-element arrays, arrays with all elements the same, and arrays with negative numbers.
This solution is optimal and straightforward, ensuring we efficiently find the desired index with minimal computational overhead.
作者声明:本文包含人工智能生成内容。