Longest subarray having sum K | Set 2 | Java program for the above approach ; To store the prefix sum array ; Function for searching the lower bound of the subarray ; Iterate until low less than equal to high ; For each mid finding sum of sub array less than or equal to k ; Return the final answer ; Function to find the length of subarray with sum K ; Initialize sum to 0 ; Push the prefix sum of the array arr [ ] in prefix [ ] ; Search r for each i ; Update ans ; Print the length of subarray found in the array ; Driver Code ; Given array arr [ ] ; Given sum K ; Function call
import java . util . * ; class GFG { static Vector < Integer > v = new Vector < Integer > ( ) ; static int bin ( int val , int k , int n ) { int lo = 0 ; int hi = n ; int mid ; int ans = - 1 ; while ( lo <= hi ) { mid = lo + ( hi - lo ) / 2 ; if ( v . get ( mid ) - val <= k ) { lo = mid + 1 ; ans = mid ; } else hi = mid - 1 ; } return ans ; } static void findSubarraySumK ( int arr [ ] , int N , int K ) { int sum = 0 ; v . add ( 0 ) ; for ( int i = 0 ; i < N ; i ++ ) { sum += arr [ i ] ; v . add ( sum ) ; } int l = 0 , ans = 0 , r ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) { r = bin ( v . get ( i ) , K , N ) ; ans = Math . max ( ans , r - i ) ; } System . out . print ( ans ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 6 , 8 , 14 , 9 , 4 , 11 , 10 } ; int N = arr . length ; int K = 13 ; findSubarraySumK ( arr , N , K ) ; } }