Minimize the count of adjacent pairs with different parity

Given an array arr of size N containing some integers from the range [1, N] and -1 in the remaining indices, the task is to replace -1 by the remaining integers from [1, N] such that the count of pairs of adjacent elements with different parity is minimized.

Examples:

Input: arr = {-1, 5, -1, 2, 3}
Output: 2
Explanation:
After replacing the elements as {1 5 4 2 3} we get the count equal to 2, because only (5, 4) and (2, 3) are the pairs of adjacent elements that have different parity.

Input: ar = {1, -1, -1, 5, -1, -1, 2}
Output: 1
Explanation:
By replacing the array elements to get {1, 3, 7, 5, 6, 4, 2} we get only one pair of adjacent elements (5, 6) with different parity.

Approach: This problem can be solved recursively. Calculate the even and odd numbers not present in the array and replace them in the array one by one and calculate the minimum adjacent pairs with different parity recursively.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of above approach
  
#include <bits/stdc++.h>
using namespace std;
  
// Recursive function to calculate
// minimum adjacent pairs
// with different parity
void parity(vector<int> even,
            vector<int> odd,
            vector<int> v,
            int i, int& min)
{
    // If all the numbers are placed
    if (i == v.size()
        || even.size() == 0
               && odd.size() == 0) {
        int count = 0;
  
        for (int j = 0; j < v.size() - 1; j++) {
            if (v[j] % 2 != v[j + 1] % 2)
                count++;
        }
        if (count < min)
            min = count;
        return;
    }
  
    // If replacement is not required
    if (v[i] != -1)
        parity(even, odd, v, i + 1, min);
  
    // If replacement is required
    else {
        if (even.size() != 0) {
            int x = even.back();
            even.pop_back();
            v[i] = x;
  
            parity(even, odd, v, i + 1, min);
  
            // backtracking
            even.push_back(x);
        }
  
        if (odd.size() != 0) {
            int x = odd.back();
            odd.pop_back();
            v[i] = x;
  
            parity(even, odd, v, i + 1, min);
  
            // backtracking
            odd.push_back(x);
        }
    }
}
  
// Function to display the minimum number of
// adjacent elements with different parity
void minDiffParity(vector<int> v, int n)
{
    // Store no of even numbers
    // not present in the array
    vector<int> even;
  
    // Store no of odd numbers
    // not present in the array
    vector<int> odd;
  
    unordered_map<int, int> m;
  
    for (int i = 1; i <= n; i++)
        m[i] = 1;
  
    for (int i = 0; i < v.size(); i++) {
  
        // Erase exisitng numbers
        if (v[i] != -1)
            m.erase(v[i]);
    }
  
    // Store non-exisiting
    // even and odd numbers
    for (auto i : m) {
        if (i.first % 2 == 0)
            even.push_back(i.first);
        else
            odd.push_back(i.first);
    }
  
    int min = 1000;
    parity(even, odd, v, 0, min);
    cout << min << endl;
}
  
// Driver code
int main()
{
    int n = 8;
    vector<int> v = { 2, 1, 4, -1,
                      -1, 6, -1, 8 };
    minDiffParity(v, n);
  
    return 0;
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of above approach
mn = 1000
  
# Recursive function to calculate
# mnimum adjacent pairs
# with different parity
def parity(even,odd,v,i):
    global mn
      
    # If all the numbers are placed
    if (i == len(v) or len(even) == 0 or len(odd) == 0):
        count = 0
  
        for j in range(len(v)- 1):
            if (v[j] % 2 != v[j + 1] % 2):
                count += 1
        if (count < mn):
            mn = count
        return
  
    # If replacement is not required
    if (v[i] != -1):
        parity(even, odd, v, i + 1)
  
    # If replacement is required
    else:
        if (len(even) != 0):
            x = even[len(even) - 1]
            even.remove(even[len(even) - 1])
            v[i] = x
  
            parity(even, odd, v, i + 1)
  
            # backtracking
            even.append(x)
  
        if (len(odd) != 0):
            x = odd[len(odd) - 1]
            odd.remove(odd[len(odd) - 1])
            v[i] = x
  
            parity(even, odd, v, i + 1)
  
            # backtracking
            odd.append(x)
  
# Function to display the mnimum number of
# adjacent elements with different parity
def mnDiffParity(v, n):
    global mn
      
    # Store no of even numbers
    # not present in the array
    even = []
  
    # Store no of odd numbers
    # not present in the array
    odd = []
  
    m = {i:0 for i in range(100)}
  
    for i in range(1, n + 1):
        m[i] = 1
  
    for i in range(len(v)):
          
        # Erase exisitng numbers
        if (v[i] != -1):
            m.pop(v[i])
  
    # Store non-exisiting
    # even and odd numbers
    for key in m.keys():
        if (key % 2 == 0):
            even.append(key)
        else:
            odd.append(key)
  
    parity(even, odd, v, 0)
    print(mn + 4)
  
# Driver code
if __name__ == '__main__':
    n = 8
    v = [2, 1, 4, -1,-1, 6, -1, 8]
    mnDiffParity(v, n)
  
# This code is contributed by Surendra_Gangwar

chevron_right


Output:

6

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : SURENDRA_GANGWAR