Number of subarrays whose minimum and maximum are same | calculate the no of contiguous subarrays which has same minimum and maximum ; stores the answer ; loop to traverse from 0 - n ; start checking subarray from next element ; traverse for finding subarrays ; if the elements are same then we check further and keep a count of same numbers in ' r ' ; the no of elements in between r and i with same elements . ; the no of subarrays that can be formed between i and r ; again start checking from the next index ; returns answer ; Driver Code
< ? php function calculate ( $ a , $ n ) { $ ans = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { $ r = $ i + 1 ; for ( $ j = $ r ; $ j < $ n ; $ j ++ ) { if ( $ a [ $ i ] == $ a [ $ j ] ) $ r += 1 ; else break ; } $ d = $ r - $ i ; $ ans += ( $ d * ( $ d + 1 ) / 2 ) ; $ i = $ r - 1 ; } return $ ans ; } $ a = array ( 2 , 4 , 5 , 3 , 3 , 3 ) ; $ n = count ( $ a ) ; echo calculate ( $ a , $ n ) ; ? >