Smallest Subarray with Sum K from an Array | Java Program to implement the above approach ; Function to find the length of the smallest subarray with sum K ; Stores the frequency of prefix sums in the array ; Initialize len as Integer . MAX_VALUE ; If sum of array till i - th index is less than K ; No possible subarray exists till i - th index ; Find the exceeded value ; If exceeded value is zero ; Driver Code
import java . util . * ; class GFG { static int subArraylen ( int arr [ ] , int n , int K ) { HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; mp . put ( arr [ 0 ] , 0 ) ; for ( int i = 1 ; i < n ; i ++ ) { arr [ i ] = arr [ i ] + arr [ i - 1 ] ; mp . put ( arr [ i ] , i ) ; } int len = Integer . MAX_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] < K ) continue ; else { int x = K - arr [ i ] ; if ( x == 0 ) len = Math . min ( len , i ) ; if ( mp . containsValue ( x ) ) continue ; else { len = Math . min ( len , i ) ; } } } return len ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 4 , 3 , 2 , 4 , 1 } ; int n = arr . length ; int K = 7 ; int len = subArraylen ( arr , n , K ) ; if ( len == Integer . MAX_VALUE ) { System . out . print ( " - 1" ) ; } else { System . out . print ( len + "NEW_LINE"); } } }