Approach :
As the order of (x,y) matters (means y should always occur after x )
First Lets Create an array 'arr' which is used to store the occurrence of y from index 'i' .
Initially, all values in arr are zero. if(a[n-1]==y) update arr[n-1] as 1 .
Now iterate the given array 'a' in reverse order from n-1 to 0 .
if current element is equal to y just update arr[i] as arr[i+1]+1 .
else copy the arr[i+1] into arr[i]
for example if given array is { 1, 2 , 3 , 2 , 4, 2} and (x,y) as (1,2)
then arr looks like { 3, 3, 3,2, 1, 1} (every element indicates the no of times y occurred from that position towards the right here arr[0] = 3 means y(i.e 2) occurred 3 times from 0th position )
after getting the above-mentioned array 'arr'.
we can start calculating the answer
count =0 (answer to be printed)
just do the following process :
iterate the original array from left to right i.e from 0 to n-2;
and check if current element is equal to 'x' if it is just increment the ans with arr[i+1] (arr[i+1] indicates no of times 'y' occured from that position )
Finally output the count
Code:
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
int n=7;
vector<int> a={100,200,300,10000,5,5,200};
int x,y;
x=100,y=200;
vector<int> arr(n);
if(a[n-1]==y) arr[n-1]=1;
for(int i=n-2;i>=0;i--)
{
if(a[i]==y)
arr[i]=arr[i+1]+1;
else arr[i]=arr[i+1];
}
int count=0;
for(int i=0;i<n-1;i++)
{
if(a[i]==x)
{
count+=arr[i+1];
}
}
cout<<count<<endl;
return 0;
}
Input 1 : {100,200,300,10000,5,5,200} (x,y)= (100,200)
output 1: 2
input 2 :{ 1, 2 , 2 , 1 ,2 , 2 , 3} (x,y)=(1,2)
output 2 : 6