Smallest subarray from a given Array with sum greater than or equal to K | Set 2 | C ++ 14 program for the above approach ; Function to find the smallest subarray sum greater than or equal to target ; Base Case ; If sum of the array is less than target ; If target is equal to the sum of the array ; Required condition ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int smallSumSubset ( vector < int > data , int target , int maxVal ) { int sum = 0 ; for ( int i : data ) sum += i ; if ( target <= 0 ) return 0 ; else if ( sum < target ) return maxVal ; else if ( sum == target ) return data . size ( ) ; else if ( data [ 0 ] >= target ) return 1 ; else if ( data [ 0 ] < target ) { vector < int > temp ; for ( int i = 1 ; i < data . size ( ) ; i ++ ) temp . push_back ( data [ i ] ) ; return min ( smallSumSubset ( temp , target , maxVal ) , 1 + smallSumSubset ( temp , target - data [ 0 ] , maxVal ) ) ; } } int main ( ) { vector < int > data = { 3 , 1 , 7 , 1 , 2 } ; int target = 11 ; int val = smallSumSubset ( data , target , data . size ( ) + 1 ) ; if ( val > data . size ( ) ) cout << -1 ; else cout << val ; }