Minimum removal of elements from end of an array required to obtain sum K | C # 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
using System ; using System . Collections . Generic ; 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 ) { Console . WriteLine ( - 1 ) ; return ; } if ( K == sum ) { for ( int i = 0 ; i < N ; i ++ ) { Console . Write ( A [ i ] + " ▁ " ) ; } return ; } int tar = sum - K ; Dictionary < int , int > um = new Dictionary < int , int > ( ) ; um [ 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 [ cur - tar ] > maxi ) { maxi = i - um [ cur - tar ] ; right = i ; left = um [ cur - tar ] ; } if ( ! um . ContainsKey ( cur ) ) um [ cur ] = i ; } if ( maxi == - 1 ) Console . Write ( - 1 ) ; else { for ( int i = 0 ; i <= left ; i ++ ) Console . Write ( A [ i ] + " ▁ " ) ; for ( int i = 0 ; i < right ; i ++ ) Console . Write ( A [ N - i - 1 ] + " ▁ " ) ; } } static public void Main ( ) { int N = 7 ; int [ ] A = { 3 , 2 , 1 , 1 , 1 , 1 , 3 } ; int K = 10 ; minSizeArr ( A , N , K ) ; } }