Absolute Distinct Numbers

You may want to have an iterative solution. Start from both ends and work your way inward toward 0.

#include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>

size_t solution( const std::vector< int > & A )
{
    std::vector< int >::const_iterator f( A.begin() );
    std::vector< int >::const_reverse_iterator b( A.rbegin() );

    size_t result = 0;
    if( A.size() )
        for( ; ( f != A.end() ) && ( b != A.rend() ); )
        {
            if( *f >= 0 )
                return result + ( ( A.end() - f ) - ( b - A.rbegin() ) );
            else if( *b <= 0 )
                return result + ( ( A.rend() - b ) - ( f - A.begin() ) );
            else if( *f == -*b )
                ++result, ++f, ++b;
            else if( *f > -*b )
                ++result, ++b;
            else
                ++result, ++f;
        }
    return result;
}


int main( int, char ** )
{
    std::cout << solution( std::vector< int >{ -5, -3, -1, 0, 3, 6} ) << std::endl;
    std::cout << solution( std::vector< int >{ -5, -3, -1, 0, 1, 3, 6} ) << std::endl;
    std::cout << solution( std::vector< int >{ -5, -3, -1, 0, 2, 3, 6} ) << std::endl;
    std::cout << solution( std::vector< int >{ -5, -3, -1, 3, 6} ) << std::endl;
    std::cout << solution( std::vector< int >{ -5, -3, -1, 0, 3, 4, 5} ) << std::endl;
    return 0;
}

Browse More Popular Posts

Leave a Comment