Find all possible subarrays having product less than or equal to K | C ++ program to implement the above approach ; Function to return all possible subarrays having product less than or equal to K ; Store the required subarrays ; Stores the product of current subarray ; Stores the starting index of the current subarray ; Check for empty array ; Iterate over the array ; Calculate product ; If product exceeds K ; Reduce product ; Increase starting index of current subarray ; Stores the subarray elements ; Store the subarray elements ; Add the subarrays to the list ; Return the final list of subarrays ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < vector < int > > maxSubArray ( int arr [ ] , int n , int K ) { vector < vector < int > > solution ; int multi = 1 ; int start = 0 ; if ( n <= 1 K < 0 ) { return solution ; } for ( int i = 0 ; i < n ; i ++ ) { multi = multi * arr [ i ] ; while ( multi > K ) { multi = multi / arr [ start ] ; start ++ ; } vector < int > list ; for ( int j = i ; j >= start ; j -- ) { list . insert ( list . begin ( ) , arr [ j ] ) ; solution . push_back ( list ) ; } } return solution ; } int main ( ) { int arr [ ] = { 2 , 7 , 1 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 7 ; vector < vector < int > > v = maxSubArray ( arr , n , K ) ; cout << " [ " ; bool first = true ; for ( auto x : v ) { if ( ! first ) { cout << " , ▁ " ; } else { first = false ; } cout << " [ " ; bool ff = true ; for ( int y : x ) { if ( ! ff ) { cout << " , ▁ " ; } else { ff = false ; } cout << y ; } cout << " ] " ; } cout << " ] " ; return 0 ; }