Number of subarrays whose minimum and maximum are same | CPP program to count number of subarrays having same minimum and maximum . ; 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 ; drive program to test the above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int calculate ( int a [ ] , int n ) { int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int r = i + 1 ; for ( int j = r ; j < n ; j ++ ) { if ( a [ i ] == a [ j ] ) r += 1 ; else break ; } int d = r - i ; ans += ( d * ( d + 1 ) / 2 ) ; i = r - 1 ; } return ans ; } int main ( ) { int a [ ] = { 2 , 4 , 5 , 3 , 3 , 3 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << calculate ( a , n ) ; return 0 ; }