Smallest subarray from a given Array with sum greater than or equal to K | Set 2 | Java program for the above approach ; 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
import java . util . * ; class GFG { static int minlt ( int [ ] arr , int target , int n ) { int [ ] [ ] dp = new int [ arr . length + 1 ] [ target + 1 ] ; for ( int [ ] row : dp ) Arrays . fill ( row , - 1 ) ; for ( int i = 0 ; i < arr . length + 1 ; i ++ ) dp [ i ] [ 0 ] = 0 ; for ( int j = 0 ; j < target + 1 ; j ++ ) dp [ 0 ] [ j ] = Integer . MAX_VALUE ; for ( int i = 1 ; i <= arr . length ; i ++ ) { for ( int 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 ] ] ) != Integer . MAX_VALUE ? ( dp [ i ] [ j - arr [ i - 1 ] ] + 1 ) : Integer . MAX_VALUE ) ; } } } if ( dp [ arr . length ] [ target ] == Integer . MAX_VALUE ) { return - 1 ; } else { return dp [ arr . length ] [ target ] ; } } public static void main ( String [ ] args ) { int [ ] arr = { 2 , 3 , 5 , 4 , 1 } ; int target = 11 ; int n = arr . length ; System . out . print ( minlt ( arr , target , n ) ) ; } }