1

Let A be an array with N entries. We consider continuous subarrays of it, these must be continuous , meaning they start at some index I and end on some index J. Denote m(I,J) the minimum element of the subarray starting at I and ending on J (contatining elements at index I and J inclusive). Find the maximum among m(I,J)*(J-I+1). J-I+1 is the subarray length.

Instead of running a loop over I and J and look for which has the minimum there should be a better algorithm in O(N) time. How can I do it? I am thinking about a thing like sliding window... First I pick the first element, I sucessively increase the width of the sliding window as long as the first element remains subarray minimum. That means that I will only have greater values. And I would eventually try to get rid of first element from sliding window to check whether greater elements lead to greater results. But how do I do it precisely?

kryomaxim
  • 119
  • 4

1 Answers1

2
  1. Traverse the array. For each element, calculate the index of the next smaller element on both sides, and store the result in arrays left[] and right[].
  2. Let the element at index i be m. For any subarray [l, r] where left[i] < l <= i and i <= r < right[i], m will be it's smallest element. Thus, of all subarrays having array[i] as the smallest element, the subarray of maximum length would be the one between (left[i], right[i]). So it's value would be array[i] * (right[i] - left[i] - 1).
  3. Calculate the global maximum of this value over the array. That would be your answer.

Edit:

This logic works for all i where array[i] >= 0. If array[i] < 0, we'll pick the shortest subarray possible for it, which will have length 1. So the value produced for it will be array[i].

Abhinav Mathur
  • 7,791
  • 3
  • 10
  • 24
  • This fixes the length of the array for any chosen minimum as the longest, which assumes all elements are positive. With negative numbers included, we may want to choose among different length subarrays for any one minimum. – גלעד ברקן Jul 14 '23 at 17:03
  • @גלעדברקן edited the answer to cover negative integers as well. – Abhinav Mathur Jul 14 '23 at 17:06