Count of subarrays having exactly K perfect square numbers | C ++ program to Count of subarrays having exactly K perfect square numbers . ; A utility function to check if the number n is perfect square or not ; Find floating point value of square root of x . ; If square root is an integer ; Function to find number of subarrays with sum exactly equal to k ; STL map to store number of subarrays starting from index zero having particular value of sum . ; To store the sum of element traverse so far ; Add current element to currsum ; If currsum = K , then a new subarray is found ; If currsum > K then find the no . of subarrays with sum currsum - K and exclude those subarrays ; Add currsum to count of different values of sum ; Return the final result ; Function to count the subarray with K perfect square numbers ; Update the array element ; If current element is perfect square then update the arr [ i ] to 1 ; Else change arr [ i ] to 0 ; Function Call ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPerfectSquare ( long double x ) { long double sr = sqrt ( x ) ; return ( ( sr - floor ( sr ) ) == 0 ) ; } int findSubarraySum ( int arr [ ] , int n , int K ) { unordered_map < int , int > prevSum ; int res = 0 ; int currsum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { currsum += arr [ i ] ; if ( currsum == K ) { res ++ ; } if ( prevSum . find ( currsum - K ) != prevSum . end ( ) ) res += ( prevSum [ currsum - K ] ) ; prevSum [ currsum ] ++ ; } return res ; } void countSubarray ( int arr [ ] , int n , int K ) { for ( int i = 0 ; i < n ; i ++ ) { if ( isPerfectSquare ( arr [ i ] ) ) { arr [ i ] = 1 ; } else { arr [ i ] = 0 ; } } cout << findSubarraySum ( arr , n , K ) ; } int main ( ) { int arr [ ] = { 2 , 4 , 9 , 2 } ; int K = 2 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countSubarray ( arr , N , K ) ; return 0 ; }