• + 0 comments

    Here is my code with comments:

    long long int solve(vector<int> arr) {
    int n=arr.size();
    int M[n];
    long long int sum=0;
    M[0]=-1;
    //Create an Array M where M[i] is the index of the closest element to the left of arr[i] that is greater than or equal to arr[i]. If there is no such element let M[i]=-1
    for(int i=1;i<n;i++){
      if(arr[i-1]>=arr[i])
      M[i]=i-1;
      else {
      int j=i-1;
      while(j>0&&arr[j]<arr[i]&&M[j]!=-1)
      j=M[j];
      M[i]=j;
      }
    }
    set<int>covered;
    for(int i=n-1;i>0;i--){
        //If a particular series of elements have been covered make sure we don't cover the index i again
        if(covered.find(i)!=covered.end())
        continue;
        int j=i;
        long k=1;
        //Find the number of elements (k) where height is same and in between all elements are of lesser height
        while(j>0&&arr[M[j]]==arr[j]){
         k++;
         covered.insert(j);
         j=M[j]; 
        }
        //Add the number of ways of making pairs from k elements multiplied by 2 (bidirectional) to the overall sum
        sum=sum+(k*(k-1));
    }
    return sum;
    }