Count segments where A[i] is rightmost or leftmost and is max

爱⌒轻易说出口 提交于 2021-02-04 21:00:41

问题


You are given an array containing N integers and you have to answer K queries. Each query contains an integer X which is the index of the (1 based index) element of the array.
Calculate the following for each query:

The number of segments containing the index X as the leftmost or the 
rightmost element and the number at the index `X` is `>=` each element
of that segment.

Segment formation example:
You have array {1, 2, 3}. The possible segments for 3 are [2,3] and [1,2,3] and [3].
The possible segments for 2 are [2] and [1,2]
I got solution by brute force. Worst case Time Complexity is O(n * k)

Input: Array[] = {4,2,1,3}, Queries[] = {1,4}
Output:  
4  
3

Explanation: 
For first query 1 all possible valid segments are [4], [4,2] , [4,2,1] and [4,2,1,3] 
hence answer is 4.  
For second query 4 all possible valid segments are [3], [1,3] and [2,1,3]
hence answer is 3.

回答1:


Preprocess two arrays in O(n), where the elements are the indexes of the next larger element for each element in the original array (one to the right and one to the left). Then answer each query in O(1).




回答2:


For each query, follow steps:

  1. process from 0 to index (-1 as your query is 1 index based)in query
  2. process from index(-1) in query to N-1

While processing sub-arrays, check that the element at an index, say i should be less than or equal to element at index in your query. If yes, then you are safe to print it.



来源:https://stackoverflow.com/questions/64026440/count-segments-where-ai-is-rightmost-or-leftmost-and-is-max

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!