Given an array arr[] of size N and an integer K, the task is to split the given array into maximum possible subarrays having equal count of even and odd elements such that the cost to split the array does not exceed K.
The cost to split an array into a subarray is the difference between the last and first elements of the subarrays respectively.
Examples:
Input: arr[] = {1, 2, 5, 10, 15, 20}, K = 4Â
Output: 1Â
Explanation:Â
The optimal way is to split the array between 2 and 5.Â
So it splits into {1, 2} and {5, 10, 15, 20}.Â
Also, both the subarrays contain an equal number of even and odd elements. The cost of the split is abs(2 – 5) = 3 which is ? K.
Input: arr[] = {1, 2, 3, 4, 5, 6}, K = 100Â
Output: 2Â
Explanation:Â
The optimal way is to make two splits such that the subarrays formed are {1, 2}, {3, 4}, {5, 6}.Â
The total cost is abs(2 – 3) + abs(4 – 5) = 2
Naive Approach: The simplest approach to solve this problem is as follows:
- Split the array at every index and check if the cost is less than K or not.
- If the cost is less than K, then check if the number of odd and even elements in the subarray are equal or not.
- Now check if another split is possible or not by repeating the same steps.
- After checking all possible splits, print the minimum cost which add up to a sum less than K.
Time Complexity: O(N2)Â
Auxiliary Space: O(1)
Efficient Approach: The idea is to maintain the counters which store the number of even numbers and odd numbers in the array. Below are the steps:
- Initialize an array (say poss[]) which stores the cost of all possible splits.
- Traverse through the array arr[]. For every index, check if the subarray up to this index and the subarray starting from the next index has equal count of odd and even elements.
- If the above condition satisfies, then a split is possible. Store the cost associated with this split in poss[].
- Repeat the above steps for all the elements in the array and store the costs of every split.
- Cost of split at index i can be obtained by abs(arr[i + 1] – arr[i]).
- Now, in order to find the maximum number of possible splits, sort the array poss[] that contains the costs of each possible split.
- Now select all minimum costs from poss[] whose sum is less than or equal to K.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; Â
// Function to find the cost of // splitting the arrays into subarray // with cost less than K int make_cuts( int arr[], int n, int K) {     // Store the possible splits     int ans = 0; Â
    // Stores the cost of each split     vector< int > poss; Â
    // Stores the count of even numbers     int ce = 0; Â
    // Stores the count     // of odd numbers     int co = 0; Â
    for ( int x = 0; x < n - 1; x++) { Â
        // Count of odd & even elements         if (arr[x] % 2 == 0)             ce++;         else             co++; Â
        // Check the required conditions         // for a valid split         if (ce == co && co > 0             && ce > 0) {             poss.push_back(                 abs (arr[x]                     - arr[x + 1]));         }     } Â
    // Sort the cost of splits     sort(poss.begin(), poss.end()); Â
    // Find the minimum split costs     // adding up to sum less than K     for ( int x : poss) {         if (K >= x) {             ans++;             K -= x;         }         else             break ;     }     return ans; } Â
// Driver Code int main() { Â Â Â Â // Given array and K Â Â Â Â int N = 6; Â Â Â Â int K = 4; Â
    int arr[] = { 1, 2, 5, 10, 15, 20 }; Â
    // Function Call     cout << make_cuts(arr, N, K); } |
Java
// Java program for the above approach import java.util.*; Â
class GFG{ Â
// Function to find the cost of // splitting the arrays into subarray // with cost less than K static int make_cuts( int arr[], int n, int K) {          // Store the possible splits     int ans = 0 ; Â
    // Stores the cost of each split     Vector<Integer> poss = new Vector<Integer>(); Â
    // Stores the count of even numbers     int ce = 0 ; Â
    // Stores the count     // of odd numbers     int co = 0 ; Â
    for ( int x = 0 ; x < n - 1 ; x++)     {                  // Count of odd & even elements         if (arr[x] % 2 == 0 )             ce++;         else             co++;                      // Check the required conditions         // for a valid split         if (ce == co && co > 0 && ce > 0 )         {             poss.add(Math.abs(arr[x] -                               arr[x + 1 ]));         }     } Â
    // Sort the cost of splits     Collections.sort(poss); Â
    // Find the minimum split costs     // adding up to sum less than K     for ( int x : poss)     {         if (K >= x)         {             ans++;             K -= x;         }         else             break ;     }     return ans; } Â
// Driver Code public static void main(String[] args) { Â Â Â Â Â Â Â Â Â // Given array and K Â Â Â Â int N = 6 ; Â Â Â Â int K = 4 ; Â
    int arr[] = { 1 , 2 , 5 , 10 , 15 , 20 }; Â
    // Function call     System.out.print(make_cuts(arr, N, K)); } } Â
// This code is contributed by Amit Katiyar |
Python3
# Python3 program for the above approach Â
# Function to find the cost of # splitting the arrays into subarray # with cost less than K def make_cuts(arr, n, K): Â
    # Store the possible splits     ans = 0 Â
    # Stores the cost of each split     poss = [] Â
    # Stores the count of even numbers     ce = 0 Â
    # Stores the count     # of odd numbers     co = 0 Â
    for x in range (n - 1 ): Â
        # Count of odd & even elements         if (arr[x] % 2 = = 0 ):             ce + = 1         else :             co + = 1 Â
        # Check the required conditions         # for a valid split         if (ce = = co and co > 0 and ce > 0 ):             poss.append( abs (arr[x] -                             arr[x + 1 ])) Â
    # Sort the cost of splits     poss.sort() Â
    # Find the minimum split costs     # adding up to sum less than K     for x in poss:         if (K > = x):             ans + = 1             K - = x         else :             break Â
    return ans Â
# Driver Code Â
# Given array and K N = 6 K = 4 Â
arr = [ 1 , 2 , 5 , 10 , 15 , 20 ] Â
# Function call print (make_cuts(arr, N, K)) Â
# This code is contributed by Shivam Singh |
C#
// C# program for the above approach using System; using System.Collections.Generic; Â
class GFG{ Â
// Function to find the cost of // splitting the arrays into subarray // with cost less than K static int make_cuts( int []arr, int n, int K) {          // Store the possible splits     int ans = 0; Â
    // Stores the cost of each split     List< int > poss = new List< int >(); Â
    // Stores the count of even numbers     int ce = 0; Â
    // Stores the count     // of odd numbers     int co = 0; Â
    for ( int x = 0; x < n - 1; x++)     {                  // Count of odd & even elements         if (arr[x] % 2 == 0)             ce++;         else             co++;                      // Check the required conditions         // for a valid split         if (ce == co && co > 0 && ce > 0)         {             poss.Add(Math.Abs(arr[x] -                               arr[x + 1]));         }     } Â
    // Sort the cost of splits     poss.Sort(); Â
    // Find the minimum split costs     // adding up to sum less than K     foreach ( int x in poss)     {         if (K >= x)         {             ans++;             K -= x;         }         else             break ;     }     return ans; } Â
// Driver Code public static void Main(String[] args) { Â Â Â Â Â Â Â Â Â // Given array and K Â Â Â Â int N = 6; Â Â Â Â int K = 4; Â
    int []arr = { 1, 2, 5, 10, 15, 20 }; Â
    // Function call     Console.Write(make_cuts(arr, N, K)); } } Â
// This code is contributed by Amit Katiyar |
Javascript
<script> Â
// Javascript program for the above approach Â
// Function to find the cost of // splitting the arrays into subarray // with cost less than K Â
function make_cuts(arr, n, K) {     // Store the possible splits     var ans = 0; Â
    // Stores the cost of each split     var poss = []; Â
    // Stores the count of even numbers     var ce = 0; Â
    // Stores the count     // of odd numbers     var co = 0;     var x;     for (x = 0; x < n - 1; x++) { Â
        // Count of odd & even elements         if (arr[x] % 2 == 0)             ce++;         else             co++; Â
        // Check the required conditions         // for a valid split         if (ce == co && co > 0             && ce > 0) {             poss.push(                 Math.abs(arr[x]                     - arr[x + 1]));         }     } Â
    // Sort the cost of splits     poss.sort(); Â
    var i;     // Find the minimum split costs     // adding up to sum less than K     for (i=0;i<poss.length;i++){         if (K >= poss[i]) {             ans++;             K -= poss[i];         }          else             break ;     }     return ans; } Â
// Driver Code Â
    // Given array and K     var N = 6;     var K = 4; Â
    var arr = [1, 2, 5, 10, 15, 20]; Â
    // Function Call     document.write(make_cuts(arr, N, K)); Â
// This code is contributed by bgangwar59. </script> |
1
Time Complexity: O(N log(N))Â
Auxiliary Space: O(N)
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!