Absolute distinct count in a sorted array | 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
< ? php function distinctCount ( $ arr , $ n ) { $ count = $ n ; $ 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 ; } $ arr = array ( -2 , -1 , 0 , 1 , 1 ) ; $ n = sizeof ( $ arr ) ; echo " Count ▁ of ▁ absolute ▁ distinct ▁ values ▁ : ▁ " . distinctCount ( $ arr , $ n ) ; ? >