mediumArraysPattern: Finding the maximum/minimum index with specific conditions

Peak Index in Array Solution

Problem Statement

You are given an array of integers `yields` where `yields[i]` represents the yield at position `i`. Find the index of the first position that is considered optimal for harvesting. A position is considered optimal if its yield is strictly higher than its neighboring positions. If a position's yield is equal to its neighbors, it is still considered optimal if its yield is the highest among all positions with the same yield.

Examples

Example 1:
Input:[1, 3, 2, 1]
Output:1
Explanation: The yield at index 1 is 3, which is higher than its neighbors 1 and 2, making it optimal.
Example 2:
Input:[1, 2, 3, 1]
Output:2
Explanation: The yield at index 2 is 3, which is higher than its neighbors 2 and 1, making it optimal.
Example 3:
Input:[1, 2, 1, 3, 5, 6, 4]
Output:5
Explanation: The yield at index 5 is 6, which is higher than its neighbors 5 and 4, making it optimal.

Constraints

  • The length of the input array will be in the range [3, 1000].
  • Each element in the array will be an integer in the range [1, 1000].
Time: O(n) Space: O(1)
An optimized approach would involve iterating through the array and keeping track of the maximum yield and its index, while also considering the conditions for an optimal position, resulting in a time complexity of O(n). This approach is more efficient and scalable for large inputs.

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

No solution code is currently loaded.
Complete this code in the workspace editor.