ARRAY HALVES - Failing test case

I was attempting the problem Array halves, code: ARRHALVES. The second last test case comes out to be erroneous but I’m unable to spot any error in the logic. Any help or hint will be highly appreciated :bear:

ARRAY HALVES

#include<bits/stdc++.h>
#define ll long long
using namespace std;

int main(){
    
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    
    int t;
    cin>>t;
    
    while(t--){
        int n,sum=0;
        int input;
        vector <int> freq;
        cin>>n;
        
        for(int i=0;i<2*n;++i){
            cin>>input;
            if(input>n){
                freq.push_back(i);
            }
        }
        
        //creating a vector of the indexes of all the elements which are greater than n
        
        sort(freq.begin(),freq.end(),greater <int> ());
        
        //sorting the vector in descending order
        
        
        n+=n-1;
        
        //the max index is 2*n-1
     
        for(auto d: freq){
           if(!freq.empty()){
                sum+=n-d;
                --n;
           }
            
        }
        
        //transporting each misplaced element to the last, then to the second last and so on. 
        
        cout<<sum<<"\n";
        
        //printing the sum.
    }
    return 0;
}

@anon42694502
plzz refer my c++ solution for debugging

#include <bits/stdc++.h>
using namespace std;

int main() {
	// your code goes here
	int t;
	cin>>t;
	while(t--)
	{
	    int n;
	    cin>>n;
	    vector<int> a;
	    for(int i=0;i<2*n;i++)
	    {
	        int x;
	        cin>>x;
	        a.push_back(x);
	    }
	    long long int ans=0;
	    for(int i=n-1,j=n;i>=0&&j<(2*n);i--,j++)
	    {
	        if(a[i]<=n&&a[j]>n)
	        {
	            continue;
	        }
	        else if(a[i]>n&&a[j]>n)
	        {
	            i++;
	        }
	        else if(a[i]<=n&&a[j]<=n)
	        {
	            j--;
	        }
	        else
	        {
	            ans+=(j-i);
	        }
	    }
	    cout<<ans<<endl;
	}
	return 0;
}

hey, just found the error. had to change the datatype to long long​:sob::sob:

1 Like