![]() |
VOOZH | about |
Given an array arr[] of size N, the task is to find the number of prefix arrays whose maximum is less than the maximum element in the remaining suffix array.
Examples:
Input: arr[] = {2, 3, 4, 8, 1, 4}
Output: 3
Explanation:
Prefix array = {2}, {2, 3}, {2, 3, 4}, {2, 3, 4, 8}, {2, 3, 4, 8, 1}
Respective Suffix = {3, 4, 8, 1, 4}, {4, 8, 1, 4}, {8, 1, 4}, {1, 4}, {4}
Only the first 3 the prefix arrays have maximum valued element less than the maximum value element in the respective suffix array.Input: arr[] = {4, 4, 4, 4, 5}
Output: 4
Naive Approach: The simplest approach is to find all possible prefixes and suffixes of the given array and count the number of indices where maximum element in the prefix array is less than the maximum element in the suffix array.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is to store the maximum value for every prefix and suffix of the array and then calculate the number of prefix arrays with a maximum value less than its corresponding suffix array. Follow the steps below to solve the problem:
Below is the implementation of the above approach:
3
Time Complexity: O(N)
Auxiliary Space: O(N)