Count of minimum reductions required to get the required sum K | Java program to find the count of minimum reductions required to get the required sum K ; Function to return the count of minimum reductions ; If the sum is already less than K ; Sort in non - increasing order of difference ; Driver code ; Function Call
import java . util . * ; class GFG { static int countReductions ( ArrayList < int [ ] > v , int K ) { int sum = 0 ; for ( int [ ] i : v ) { sum += i [ 0 ] ; } if ( sum <= K ) { return 0 ; } Collections . sort ( v , ( a , b ) -> Math . abs ( b [ 0 ] - b [ 1 ] ) - Math . abs ( a [ 0 ] - a [ 1 ] ) ) ; int i = 0 ; while ( sum > K && i < v . size ( ) ) { sum -= ( v . get ( i ) [ 0 ] - v . get ( i ) [ 1 ] ) ; i ++ ; } if ( sum <= K ) return i ; return - 1 ; } public static void main ( String [ ] args ) { int N = 4 , K = 25 ; ArrayList < int [ ] > v = new ArrayList < > ( ) ; v . add ( new int [ ] { 10 , 5 } ) ; v . add ( new int [ ] { 20 , 9 } ) ; v . add ( new int [ ] { 12 , 10 } ) ; v . add ( new int [ ] { 4 , 2 } ) ; System . out . println ( countReductions ( v , K ) ) ; } }