Count subarrays having a single distinct element that can be obtained from a given array | Java program for the above approach ; Function to count subarrays of single distinct element into which given array can be split ; Stores the count ; Stores frequency of array elements ; Traverse the array ; Traverse the map ; Increase count of subarrays by ( frequency - 1 ) ; Driver Code
import java . io . * ; import java . util . * ; class GFG { static void divisionalArrays ( int arr [ ] , int N ) { int sum = N ; HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( mp . containsKey ( arr [ i ] ) ) { mp . put ( arr [ i ] , mp . get ( arr [ i ] ) + 1 ) ; } else { mp . put ( arr [ i ] , 1 ) ; } } for ( Map . Entry x : mp . entrySet ( ) ) { if ( ( int ) x . getValue ( ) > 1 ) { sum += ( int ) x . getValue ( ) - 1 ; } } System . out . println ( sum ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 1 , 3 } ; int N = arr . length ; divisionalArrays ( arr , N ) ; } }