Smallest subarray from a given Array with sum greater than or equal to K | Set 2 | Function to find the smallest subarray with sum greater than or equal target ; DP table to store the computed subproblems ; Initialize first column with 0 ; Initialize first row with 0 ; Check for invalid condition ; Fill up the dp table ; Print the minimum length ; Driver code
function minlt ( arr , target , n ) { var dp = Array . from ( Array ( arr . length + 1 ) , ( ) => Array ( target + 1 ) . fill ( - 1 ) ) ; for ( var i = 0 ; i < arr . length + 1 ; i ++ ) dp [ i ] [ 0 ] = 0 ; for ( var j = 0 ; j < target + 1 ; j ++ ) dp [ 0 ] [ j ] = 1000000000 ; for ( var i = 1 ; i <= arr . length ; i ++ ) { for ( var j = 1 ; j <= target ; j ++ ) { if ( arr [ i - 1 ] > j ) { dp [ i ] [ j ] = dp [ i - 1 ] [ j ] ; } else { dp [ i ] [ j ] = Math . min ( dp [ i - 1 ] [ j ] , ( dp [ i ] [ j - arr [ i - 1 ] ] ) != 1000000000 ? ( dp [ i ] [ j - arr [ i - 1 ] ] + 1 ) : 1000000000 ) ; } } } if ( dp [ arr . length ] [ target ] == 1000000000 ) { return - 1 ; } else { return dp [ arr . length ] [ target ] ; } } var arr = [ 2 , 3 , 5 , 4 , 1 ] ; var target = 11 ; var n = arr . length ; document . write ( minlt ( arr , target , n ) ) ;