Problem Description
Given an integer array and an index k, the task is to find the maximum score of any subarray that contains the index k. The score of a subarray is defined as the minimum element in that subarray multiplied by the subarray’s length.
Key Insights
- The subarray must include the given index k.
- Starting from k, we can expand the subarray greedily to include as many elements as possible while keeping track of the running minimum.
- At every step, the expansion is limited by the smaller neighbor, as that will determine the new subarray minimum.
- The problem can be solved in O(n) time by two pointers expanding from the fixed index.
Space and Time Complexity
Time Complexity: O(n) Space Complexity: O(1)
Solution
The approach begins at index k with a subarray that only contains nums[k]. Two pointers (left and right) are initialized at k. At each step, decide whether to move the left pointer one step left or the right pointer one step right. Choose the direction that has a larger neighbor so that the running minimum does not drop too quickly. Update the running minimum with the minimum between the current value and the newly added element. Calculate the subarray score at every step and update the best score. Continue until both pointers have spanned the entire array.