Absolute distinct count in a sorted array | C ++ program to find absolute distinct count of an array using O ( 1 ) space . ; The function returns return number of distinct absolute values among the elements of the array ; initialize count as number of elements ; Remove duplicate elements from the left of the current window ( i , j ) and also decrease the count ; Remove duplicate elements from the right of the current window ( i , j ) and also decrease the count ; break if only one element is left ; Now look for the zero sum pair in current window ( i , j ) ; decrease the count if ( positive , negative ) pair is encountered ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int distinctCount ( int arr [ ] , int n ) { int count = n ; int i = 0 , j = n - 1 , sum = 0 ; while ( i < j ) { while ( i != j && arr [ i ] == arr [ i + 1 ] ) count -- , i ++ ; while ( i != j && arr [ j ] == arr [ j - 1 ] ) count -- , j -- ; if ( i == j ) break ; sum = arr [ i ] + arr [ j ] ; if ( sum == 0 ) { count -- ; i ++ , j -- ; } else if ( sum < 0 ) i ++ ; else j -- ; } return count ; } int main ( ) { int arr [ ] = { -2 , -1 , 0 , 1 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Count ▁ of ▁ absolute ▁ distinct ▁ values ▁ : ▁ " << distinctCount ( arr , n ) ; return 0 ; }