Number of subarrays having absolute sum greater than K | Set | C ++ implementation of the above approach ; Function to find required value ; Variable to store final answer ; Loop to find prefix - sum ; Sorting prefix - sum array ; Loop to find upper_bound for each element ; Returning final answer ; Driver code ; Function to find required value
#include <bits/stdc++.h> NEW_LINE #define maxLen  30 NEW_LINE using namespace std ; int findCnt ( int arr [ ] , int n , int k ) { int ans = 0 ; for ( int i = 1 ; i < n ; i ++ ) { arr [ i ] += arr [ i - 1 ] ; if ( arr [ i ] > k or arr [ i ] < -1 * k ) ans ++ ; } if ( arr [ 0 ] > k arr [ 0 ] < -1 * k ) ans ++ ; sort ( arr , arr + n ) ; for ( int i = 0 ; i < n ; i ++ ) ans += n - ( upper_bound ( arr , arr + n , arr [ i ] + k ) - arr ) ; return ans ; } int main ( ) { int arr [ ] = { -1 , 4 , -5 , 6 } ; int n = sizeof ( arr ) / sizeof ( int ) ; int k = 0 ; cout << findCnt ( arr , n , k ) ; }