Queries to count occurrences of maximum array element in subarrays starting from given indices

Given two arrays arr[] and q[] consisting of N integers, the task is for each query q[i] is to determine the number of times the maximum array element occurs in the subarray [q[i], arr[N – 1]].
Examples:
Input: arr[] = {5, 4, 5, 3, 2}, q[] = {1, 2, 3, 4, 5}
Output: 2 1 1 1 1
Explanation:
For the first query index start from 1. The subarray is [5, 4, 5, 3, 2], the maximum value is 5 and it’s occurrence in subarray is 2.
For the second query index start from 2. The subarray is [4, 5, 3, 2], the maximum value is 5 and it’s occurrence in subarray is 1.
For the third query index start from 3. The subarray is [5, 3, 2], the maximum value is 5 and it’s occurrence in subarray is 1.
For the forth query index start from 4. The subarray is [3, 2], the maximum value is 3 and it’s occurrence in subarray is 1.
For the fifth query index start from 5. The subarray is [2], the maximum value is 2 and it’s occurrence in subarray is 1.Input: arr[] = {2, 1, 2}, q[] = {1, 2, 3}
Output: 2 1 1
Naive Approach: The simplest approach is to traverse the array and find the maximum array element. Now, for each query q[i], traverse the subarray [q[i], arr[N – 1]], and print the count of occurrences of the maximum element in the subarray.Â
Follow the steps below to implement the above idea:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;Â
// Function to find occurrence of// max element in given subarrayvoid FreqOfMaxElement(vector<int> arr, vector<int> q){Â
    // Traverse over each query    for (int i = 0; i < q.size(); i++) {Â
        // Find the starting index of each query        int start = q[i] - 1;        int count = 0;Â
        // Find the maximum element in the range of each        // query        int maxx            = *max_element(arr.begin() + start, arr.end());Â
        // Find the occurrences of maxx element        for (int j = start; j < arr.size(); j++) {            if (arr[j] == maxx) {                count++;            }        }Â
        // Print the count        cout << count << " ";    }}Â
// Driver Codeint main(){Â Â Â Â vector<int> arr = { 5, 4, 5, 3, 2 };Â Â Â Â vector<int> q = { 1, 2, 3, 4, 5 };Â
    // Function Call    FreqOfMaxElement(arr, q);} |
Java
import java.util.*;import java.io.*;Â
Â
public class Gfg {    // Function to find occurrence of    // max element in given subarray    public static void FreqOfMaxElement(List<Integer> arr,                                        List<Integer> q)    {        // Traverse over each query        for (int i = 0; i < q.size(); i++) {            // Find the starting index of each query            int start = q.get(i) - 1;            int count = 0;Â
            // Find the maximum element in the range of each            // query            int maxx = Collections.max(arr.subList(start, arr.size()));Â
            // Find the occurrences of maxx element            for (int j = start; j < arr.size(); j++) {                if (arr.get(j) == maxx) {                    count++;                }            }Â
            // Print the count            System.out.print(count + " ");        }    }Â
    // Driver Code    public static void main(String[] args)    {        List<Integer> arr = Arrays.asList(5, 4, 5, 3, 2);        List<Integer> q = Arrays.asList(1, 2, 3, 4, 5);Â
        // Function Call        FreqOfMaxElement(arr, q);    }} |
Python3
from collections import Counter Â
def FreqOfMaxElement(arr, q):     # Traverse over each query     for i in range(len(q)):         # Find the starting index of each query         start = q[i] - 1        count = 0Â
        # Find the maximum element in the range of each query         maxx = max(arr[start:]) Â
        # Find the occurrences of maxx element         for j in range(start, len(arr)):             if arr[j] == maxx:                 count += 1Â
        # Print the count         print(count, end = " ") Â
# Driver Code if __name__ == "__main__": Â Â Â Â arr = [5, 4, 5, 3, 2] Â Â Â Â q = [1, 2, 3, 4, 5] Â Â Â Â FreqOfMaxElement(arr, q)Â Â Â Â Â Â Â Â Â # This code is contributed by aadityaburujwale. |
C#
// C# program for the above approachÂ
using System;using System.Linq;using System.Collections.Generic;Â
class GFG {         // Function to find occurrence of    // max element in given subarray    static void FreqOfMaxElement(int[] arr,int[] q)    {             // Traverse over each query        for (int i = 0; i < q.Length; i++) {                 // Find the starting index of each query            int start = q[i] - 1;            int count = 0;                 // Find the maximum element in the range of each            // query            int maxx=-1;            for(int j=start; j<arr.Length; j++)                maxx=Math.Max(maxx, arr[j]);                 // Find the occurrences of maxx element            for (int j = start; j < arr.Length; j++) {                if (arr[j] == maxx) {                    count++;                }            }                 // Print the count            Console.Write(count + " ");        }    }         // Driver Code    public static void Main (string[] args)     {        int[] arr = { 5, 4, 5, 3, 2 };        int[] q = { 1, 2, 3, 4, 5 };             // Function Call        FreqOfMaxElement(arr, q);    }} |
Javascript
// Javascript program for the above approachÂ
// Function to find occurrence of// max element in given subarrayfunction FreqOfMaxElement(arr, q){Â
    // Traverse over each query    for (let i = 0; i < q.length; i++) {Â
        // Find the starting index of each query        let start = q[i] - 1;        let count = 0;Â
        // Find the maximum element in the range of each        // query        let maxx=Number.MIN_SAFE_INTEGER;                     for(let i=start; i<arr.length; i++)        {            maxx=Math.max(arr[i], maxx);        }        // Find the occurrences of maxx element        for (let j = start; j < arr.length; j++) {            if (arr[j] == maxx) {                count++;            }        }Â
        // Print the count        document.write(count);        document.write(" ");    }}Â
// Driver Codelet arr = [ 5, 4, 5, 3, 2 ];let q = [ 1, 2, 3, 4, 5 ];Â
// Function CallFreqOfMaxElement(arr, q); |
2 1 1 1 1
Time Complexity: O(N*Q), where N and Q are the lengths of the given array and query respectively.
Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is to use Hashing. Below are the steps:
- Create an array maxFreqVec[] to store the occurrence of the max element from given index q[i] to N.
- Traverse the array arr[] from the right and keep track of the maximum element in the array and update the array maxFreqVec[] at that index with the occurrence of that maximum element.
- After the above steps, traverse over the array q[] and print the value maxFreqVec[q[i] – 1] as the maximum element in each subarray for each query.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include<bits/stdc++.h>using namespace std;Â
// Function to find occurrence of// max element in given subarrayvoid FreqOfMaxElement(vector<int> arr,                       vector<int> q){         // Store the frequency of maximum    // element    vector<int> maxFreqVec(arr.size());Â
    int maxSoFar = INT_MIN;    int maxFreq = 0;Â
    // Traverse over the array arr[]    // from right to left    for(int i = arr.size() - 1; i >= 0; i--)     {                 // If curr element is greater        // than maxSofar        if (arr[i] > maxSoFar)        {                         // Reset maxSofar and maxFreq            maxSoFar = arr[i];            maxFreq = 1;        }Â
        // If curr is equal to maxSofar        else if (arr[i] == maxSoFar)        {                         // Increment the maxFreq            maxFreq++;        }Â
        // Update maxFreqVec[i]        maxFreqVec[i] = maxFreq;    }Â
    // Print occurrence of maximum    // element for each query    for(int k : q)    {        cout << maxFreqVec[k - 1] << " ";    }}Â
// Driver Codeint main(){    vector<int> arr = { 5, 4, 5, 3, 2 };    vector<int> q = { 1, 2, 3, 4, 5 };         // Function Call    FreqOfMaxElement(arr, q);}Â
// This code is contributed by mohit kumar 29 |
Java
// Java program for the above approachimport java.util.*;import java.lang.*;Â
class GFG {Â
    // Function to find occurrence of    // max element in given subarray    static void FreqOfMaxElement(        int[] arr, int[] q)    {Â
        // Store the frequency of maximum        // element        int[] maxFreqVec            = new int[arr.length];Â
        int maxSoFar = Integer.MIN_VALUE;        int maxFreq = 0;Â
        // Traverse over the array arr[]        // from right to left        for (int i = arr.length - 1;             i >= 0; i--) {Â
            // If curr element is greater            // than maxSofar            if (arr[i] > maxSoFar) {Â
                // Reset maxSofar and maxFreq                maxSoFar = arr[i];                maxFreq = 1;            }Â
            // If curr is equal to maxSofar            else if (arr[i] == maxSoFar) {Â
                // Increment the maxFreq                maxFreq++;            }Â
            // Update maxFreqVec[i]            maxFreqVec[i] = maxFreq;        }Â
        // Print occurrence of maximum        // element for each query        for (int k : q) {            System.out.print(                maxFreqVec[k - 1] + " ");        }    }Â
    // Driver Code    public static void main(String[] args)    {        int[] arr = { 5, 4, 5, 3, 2 };        int[] q = { 1, 2, 3, 4, 5 };Â
        // Function Call        FreqOfMaxElement(arr, q);    }} |
Python3
# Python3 program for # the above approachimport sys;Â
# Function to find occurrence# of max element in given # subarraydef FreqOfMaxElement(arr, q):       # Store the frequency of    # maximum element    maxFreqVec = [0] * (len(arr));Â
    maxSoFar = -sys.maxsize;    maxFreq = 0;Â
    # Traverse over the array    # arr from right to left    for i in range(len(arr)-1,                    -1, -1):Â
        # If curr element is        # greater than maxSofar        if (arr[i] > maxSoFar):Â
            # Reset maxSofar             # and maxFreq            maxSoFar = arr[i];            maxFreq = 1;Â
        # If curr is equal to         # maxSofar        elif (arr[i] == maxSoFar):Â
            # Increment the             # maxFreq            maxFreq += 1;Â
        # Update maxFreqVec[i]        maxFreqVec[i] = maxFreq;Â
    # Print occurrence of maximum    # element for each query    for i in range(0, len(q)):        print(maxFreqVec[q[i] - 1],              end = " ");Â
# Driver Codeif __name__ == '__main__':Â Â Â Â Â Â Â arr = [5, 4, 5, 3, 2];Â Â Â Â q = [1, 2, 3, 4, 5];Â
    # Function Call    FreqOfMaxElement(arr, q);Â
# This code is contributed by shikhasingrajput |
C#
// C# program for the // above approachusing System;class GFG{     // Function to find occurrence of// max element in given subarraystatic void FreqOfMaxElement(int[] arr,                              int[] q){  // Store the frequency of   // maximum element  int[] maxFreqVec = new int[arr.Length];Â
  int maxSoFar = Int32.MinValue;  int maxFreq = 0;Â
  // Traverse over the array arr[]  // from right to left  for (int i = arr.Length - 1;           i >= 0; i--)   {    // If curr element is greater    // than maxSofar    if (arr[i] > maxSoFar)     {      // Reset maxSofar and maxFreq      maxSoFar = arr[i];      maxFreq = 1;    }Â
    // If curr is equal to maxSofar    else if (arr[i] == maxSoFar)     {      // Increment the maxFreq      maxFreq++;    }Â
    // Update maxFreqVec[i]    maxFreqVec[i] = maxFreq;  }Â
  // Print occurrence of maximum  // element for each query  foreach (int k in q)   {    Console.Write(maxFreqVec[k - 1] +                   " ");  }}     // Driver codestatic void Main() {  int[] arr = {5, 4, 5, 3, 2};  int[] q = {1, 2, 3, 4, 5};Â
  // Function Call  FreqOfMaxElement(arr, q);  }}Â
// This code is contributed by divyeshrabadiya07 |
Javascript
<script>Â
// Javascript program for the above approach Â
// Function to find occurrence of// max element in given subarrayfunction FreqOfMaxElement(arr, q){         // Store the frequency of maximum    // element    var maxFreqVec = new Array(arr.length);    var maxSoFar = -1000000000;    var maxFreq = 0;Â
    // Traverse over the array arr[]    // from right to left    for(var i = arr.length - 1; i >= 0; i--)     {                 // If curr element is greater        // than maxSofar        if (arr[i] > maxSoFar)        {                         // Reset maxSofar and maxFreq            maxSoFar = arr[i];            maxFreq = 1;        }Â
        // If curr is equal to maxSofar        else if (arr[i] == maxSoFar)        {                         // Increment the maxFreq            maxFreq++;        }Â
        // Update maxFreqVec[i]        maxFreqVec[i] = maxFreq;    }Â
    // Print occurrence of maximum    // element for each query    q.forEach(k => {        document.write( maxFreqVec[k - 1] + " ");    });}Â
// Driver Codevar arr = [ 5, 4, 5, 3, 2 ];var q = [ 1, 2, 3, 4, 5 ];Â
// Function CallFreqOfMaxElement(arr, q);Â
// This code is contributed by rutvik_56Â
</script> |
2 1 1 1 1
Â
Time Complexity: O(N)
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



