Split an Array to maximize subarrays having equal count of odd and even elements for a cost not exceeding K | Java program for the above approach ; Function to find the cost of splitting the arrays into subarray with cost less than K ; Store the possible splits ; Stores the cost of each split ; Stores the count of even numbers ; Stores the count of odd numbers ; Count of odd & even elements ; Check the required conditions for a valid split ; Sort the cost of splits ; Find the minimum split costs adding up to sum less than K ; Driver Code ; Given array and K ; Function call
import java . util . * ; class GFG { static int make_cuts ( int arr [ ] , int n , int K ) { int ans = 0 ; Vector < Integer > poss = new Vector < Integer > ( ) ; int ce = 0 ; int co = 0 ; for ( int x = 0 ; x < n - 1 ; x ++ ) { if ( arr [ x ] % 2 == 0 ) ce ++ ; else co ++ ; if ( ce == co && co > 0 && ce > 0 ) { poss . add ( Math . abs ( arr [ x ] - arr [ x + 1 ] ) ) ; } } Collections . sort ( poss ) ; for ( int x : poss ) { if ( K >= x ) { ans ++ ; K -= x ; } else break ; } return ans ; } public static void main ( String [ ] args ) { int N = 6 ; int K = 4 ; int arr [ ] = { 1 , 2 , 5 , 10 , 15 , 20 } ; System . out . print ( make_cuts ( arr , N , K ) ) ; } }