Minimum removal of elements from end of an array required to obtain sum K | Java program for the above approach ; Function to find the smallest array that can be removed from the ends of an array to obtain sum K ; Sum of complete array ; If given number is greater than sum of the array ; If number is equal to the sum of array ; tar is sum of middle subarray ; Find the longest subarray with sum equal to tar ; If there is no subarray with sum equal to tar ; Driver Code ; Given Array ; Given target sum
import java . io . * ; import java . util . * ; class GFG { static void minSizeArr ( int A [ ] , int N , int K ) { int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) sum += A [ i ] ; if ( K > sum ) { System . out . print ( - 1 ) ; return ; } if ( K == sum ) { for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( A [ i ] + " ▁ " ) ; } return ; } int tar = sum - K ; HashMap < Integer , Integer > um = new HashMap < Integer , Integer > ( ) ; um . put ( 0 , - 1 ) ; int left = 0 , right = 0 ; int cur = 0 , maxi = - 1 ; for ( int i = 0 ; i < N ; i ++ ) { cur += A [ i ] ; if ( um . containsKey ( cur - tar ) && i - um . get ( cur - tar ) > maxi ) { maxi = i - um . get ( cur - tar ) ; right = i ; left = um . get ( cur - tar ) ; } if ( ! um . containsKey ( cur ) ) um . put ( cur , i ) ; } if ( maxi == - 1 ) System . out . println ( - 1 ) ; else { for ( int i = 0 ; i <= left ; i ++ ) System . out . print ( A [ i ] + " ▁ " ) ; for ( int i = 0 ; i < right ; i ++ ) System . out . print ( A [ N - i - 1 ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int N = 7 ; int A [ ] = { 3 , 2 , 1 , 1 , 1 , 1 , 3 } ; int K = 10 ; minSizeArr ( A , N , K ) ; } }