VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-indices-where-the-maximum-in-the-prefix-array-is-less-than-that-in-the-suffix-array/

⇱ Count indices where the maximum in the prefix array is less than that in the suffix array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count indices where the maximum in the prefix array is less than that in the suffix array

Last Updated : 23 Jul, 2025

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:

  • Initialize a variable, say ans and two arrays prefix[] and suffix[] of size N.
  • Traverse the array arr[] over the range [0, N - 1] and for each ith index in prefix[], store the maximum element as prefix[i] = max(prefix[i - 1], arr[i]).
  • Traverse the given array in the reverse order over the range [N - 1, 0] and for each ith index in suffix[], store the maximum element as suffix[i] = max(suffix[i + 1], arr[i]).
  • Now, traverse the array arr[] over the range [0, N - 2] and if prefix[i] is less than suffix[i], then increment ans by 1.
  • After completing the above steps, print the value of ans as the result.

Below is the implementation of the above approach:


Output: 
3

 

Time Complexity: O(N)
Auxiliary Space: O(N)

Comment