Open In App

Count of product operations to make adjacent Array elements of different parity

Last Updated : 26 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] consisting of N elements. At each operation, you can select any 2 adjacent elements in which both the elements are of the same parity and then delete both of them, and insert their product in the same position, the task is to find the minimum number of operations needed for this.

Examples:

Input : arr[] = {3, 5, 7, 8, 9}
Output : Minimum Operation = 2
Explanation : first we will select first 2 indices with value 3 and 5 then our new array will become {15, 7, 8, 9}and then again we will select first 2 indices and new array will be {105, 8, 9} Hence, After 2 operations every adjacent element of our array will be of different parity.

Input : arr[] = {1, 4, 7, 10}
Output : Minimum Operation = 0
Explanation : Each adjacent pair is of different parity.

Approach: To solve the problem follow the below observations:

Observations:

We know that,

  • Even * Even = Even
  • Odd * Odd = Odd
  • Odd * Even = Even

Now, If we took a closer look at each operation as well problem statement we will find that if adjacent elements are both even or both odd then we will increase our count by one. Because if they are already of different parity we don’t have to change otherwise their product will be of the same parity. 

 Below is the implementation for the above approach:

C++




// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
 
// Function for finding min operation
int minOp(int arr[], int n)
{
    int minOperation = 0;
    for (int i = 0; i < n - 1; i++) {
 
        // Checking weather parity is
        // same or different
        if ((arr[i] % 2 == arr[i + 1] % 2)) {
            minOperation++;
        }
    }
    return minOperation;
}
 
// Driver function
int main()
{
    int arr[] = { 5, 6, 2, 4, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << "Minimum Operation = " << minOp(arr, n);
    return 0;
}


Java




// Java code for the above approach:
import java.util.*;
 
class GFG {
 
  // Function for finding min operation
  public static int minOp(int arr[], int n)
  {
    int minOperation = 0;
    for (int i = 0; i < n - 1; i++) {
 
      // Checking weather parity is
      // same or different
      if ((arr[i] % 2 == arr[i + 1] % 2)) {
        minOperation++;
      }
    }
    return minOperation;
  }
 
  // Driver function
  public static void main(String[] args)
  {
    int arr[] = { 5, 6, 2, 4, 3 };
    int n = arr.length;
 
    // Function Call
    System.out.println("Minimum Operation = "
                       + minOp(arr, n));
  }
}
 
// This Code is Contributed by Prasad Kandekar(prasad264)


Python3




# Python code for the above approach:
 
# Function for finding min operation
 
 
def minOp(arr):
    n = len(arr)
    minOperation = 0
    for i in range(n-1):
 
        # Checking weather parity is
        # same or different
        if arr[i] % 2 == arr[i+1] % 2:
            minOperation += 1
 
    return minOperation
 
 
# Driver function
if __name__ == '__main__':
    arr = [5, 6, 2, 4, 3]
    n = len(arr)
 
    # Function Call
    print("Minimum Operation =", minOp(arr))
 
    # This Code is Contributed by rutikbhosale


C#




// C# code for the above approach:
using System;
 
class GFG {
  public static int minOp(int[] arr, int n)
  {
    int minOperation = 0;
    for (int i = 0; i < n - 1; i++) {
      if ((arr[i] % 2 == arr[i + 1] % 2)) {
        minOperation++;
      }
    }
    return minOperation;
  }
 
  public static void Main (string[] args) {
    int[] arr = { 5, 6, 2, 4, 3 };
    int n = arr.Length;
 
    // Function Call
    Console.WriteLine("Minimum Operation = " + minOp(arr, n));
  }
}


Javascript




// Javascript code for the above approach
 
// Function for finding min operation
function minOp(arr) {
  let minOperation = 0;
  for (let i = 0; i < arr.length - 1; i++) {
    // Checking weather parity is same or different
    if (arr[i] % 2 === arr[i + 1] % 2) {
      minOperation++;
    }
  }
  return minOperation;
}
 
// Driver function
function main() {
  const arr = [5, 6, 2, 4, 3];
  const n = arr.length;
 
  // Function Call
  console.log("Minimum Operation = " + minOp(arr));
}
 
// Invoke the driver function
main();


Output

Minimum Operation = 2










Time Complexity: O(N), where N represents the size of the given array.
Auxiliary Space: O(1), no extra space is required, so it is a constant.

Method #2:Using Bitwise Operators

  1. Initialize a variable ‘min_ops’ to 0 to count the number of operations.
     
  2. Iterate through the array from the first element to the second last element.
     
  3. Check if the parity of the current element and the next element is the same.
     
  4. If the parity is the same, multiply the larger element by 2 to make them have different parity.
     
  5. Increment the ‘min_ops’ variable by 1.
     
  6. Continue iterating till the end of the array.
     
  7. Return the ‘min_ops’ variable.

C++




// C++ code
#include <iostream>
#include <vector>
 
using namespace std;
 
// Function to find the minimum number of product operations
int min_operations(vector<int>& arr) {
    int n = arr.size();
    int min_ops = 0;
    for (int i = 0; i < n-1; i++) {
        // Check if the parity of the adjacent elements is the same
        if (((arr[i] ^ arr[i+1]) & 1) == 0) {
            // Perform the product operation
            if (arr[i] < arr[i+1]) {
                arr[i+1] *= 2;
            } else {
                arr[i] *= 2;
            }
            min_ops += 1;
        }
    }
    return min_ops;
}
// Driver code
int main() {
    vector<int> arr = {5, 6, 2, 4, 3};
    cout << "Minimum number of product operations: " << min_operations(arr) << endl;
    return 0;
}
 
// This Code is Contributed by Utkarsh Kumar


Java




import java.util.ArrayList;
import java.util.List;
 
public class GFG {
   
      // Function to find the minimum number of product operations
    public static int minOperations(List<Integer> arr) {
        int n = arr.size();
        int minOps = 0;
        for (int i = 0; i < n - 1; i++) {
           
              // Check if the parity of the adjacent elements is the same
            if (((arr.get(i) ^ arr.get(i + 1)) & 1) == 0) {
              // Perform the product operation 
              if (arr.get(i) < arr.get(i + 1)) {
                    arr.set(i + 1, arr.get(i + 1) * 2);
                } else {
                    arr.set(i, arr.get(i) * 2);
                }
                minOps += 1;
            }
        }
        return minOps;
    }
 
      // Driver code
    public static void main(String[] args) {
        List<Integer> arr = new ArrayList<>();
        arr.add(5);
        arr.add(6);
        arr.add(2);
        arr.add(4);
        arr.add(3);
        System.out.println("Minimum number of product operations: " + minOperations(arr));
    }
}


Python3




# Function to find the minimum number of product operations
def min_operations(arr):
    n = len(arr)
    min_ops = 0
    for i in range(n-1):
        # Check if the parity of the adjacent elements is the same
        if (arr[i] ^ arr[i+1]) & 1 == 0:
            # Perform the product operation
            if arr[i] < arr[i+1]:
                arr[i+1] *= 2
            else:
                arr[i] *= 2
            min_ops += 1
    return min_ops
 
# Driver code
arr = [5, 6, 2, 4, 3]
print("Minimum number of product operations:", min_operations(arr))


C#




// C# Code
using System;
using System.Collections.Generic;
 
public class GFG {
    // Function to find the minimum number of product
    // operations
    static int MinOperations(List<int> arr)
    {
        int n = arr.Count;
        int minOps = 0;
        for (int i = 0; i < n - 1; i++) {
            // Check if the parity of the adjacent elements
            // is the same
            if (((arr[i] ^ arr[i + 1]) & 1) == 0) {
                // Perform the product operation
                if (arr[i] < arr[i + 1]) {
                    arr[i + 1] *= 2;
                }
                else {
                    arr[i] *= 2;
                }
                minOps += 1;
            }
        }
        return minOps;
    }
 
    // Driver code
    static public void Main()
    {
        List<int> arr = new List<int>{ 5, 6, 2, 4, 3 };
        Console.WriteLine(
            "Minimum number of product operations: "
            + MinOperations(arr));
    }
}


Javascript




// JavaScript code for above approach
 
// Function to find the minimum number of product operations
function minOperations(arr) {
    const n = arr.length;
    let minOps = 0;
     
    for (let i = 0; i < n - 1; i++) {
        // Check if the parity of the adjacent elements is the same
        if ((arr[i] ^ arr[i + 1]) % 2 === 0) {
            // Perform the product operation
            if (arr[i] < arr[i + 1]) {
                arr[i + 1] *= 2;
            } else {
                arr[i] *= 2;
            }
            minOps += 1;
        }
    }
     
    return minOps;
}
 
// Driver code
 
const arr = [5, 6, 2, 4, 3];
console.log("Minimum number of product operations: " + minOperations(arr));
 
// This code is contributed by prasad264


Output

Minimum number of product operations: 2










Time Complexity: O(N), where N represents the size of the given array.
Auxiliary Space: O(1), no extra space is required, so it is a constant.



Similar Reads

Minimum operations required to modify the array such that parity of adjacent elements is different
Given an array A[], the task is to find the minimum number of operations required to convert the array into B[] such that for every index in B (except the last) parity(b[i]) != parity(b[i + 1]) where parity(x) = x % 3. Below is the operation to be performed: Any element from the set {1, 2} can be added to any element of the array. Examples: Input:
9 min read
Count of all subsequences having adjacent elements with different parity
Given an array arr[] of size N, the task is to find the number of non-empty subsequences from the given array such that no two adjacent elements of the subsequence have the same parity. Examples: Input: arr[] = [5, 6, 9, 7] Output: 9 Explanation: All such subsequences of given array will be {5}, {6}, {9}, {7}, {5, 6}, {6, 7}, {6, 9}, {5, 6, 9}, {5,
9 min read
Parity of count of letters whose position and frequency have same parity
Given a string S of lowercase English characters, find out whether the number of the letters whose frequencies in the string have the same parity as their positions in the English alphabet is odd or even (i.e., they have an odd frequency in the string and their position is at an odd number in the English alphabet or have even frequency and their po
8 min read
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 element
10 min read
Make parity of elements same using minimum operations
Given an array A[] of length N along with an integer X, the task is to make the parity of all the elements in A[] the same by using either of the given functions on two distinct indexed elements C and D, the minimum number of times. Operation 1: (C | D) ^ XOperation 2: (C ^ D) | X Note: It is not allowed to use both functions. Examples: Input: N =
17 min read
Minimum integer that can be obtained by swapping adjacent digits of different parity
Given an integer N, the task is to find the minimum integer that can be obtained from the given integer such that the adjacent digits of different parity can be swapped any no of times. Two digits of different parity means that they will have different remainders when divided by two.Examples: Input: N = 64432 Output: 36442 Explanation: Swap the 4th
7 min read
Check if all the elements can be made of same parity by inverting adjacent elements
Given a binary matrix. In a single operation, you are allowed to choose two adjacent elements and invert their parity. The operation can be performed any number of times. Write a program to check if all the elements of the array can be converted into a single parity. Examples: Input: a[] = {1, 0, 1, 1, 0, 1} Output: Yes Invert 2nd and 3rd elements
4 min read
Minimum value exceeding X whose count of divisors has different parity with count of divisors of X
Given an integer X, the task is to determine the minimum value of Y greater than X, such that count of divisors of X and Y have different parities. Examples: Input: X = 5Output: 9Explanation: The count of divisors of 5 and 9 are 2 and 3 respectively, which are of different parities. Input: X = 9Output: 10Explanation: The counts of divisors of 9 and
8 min read
Check if array can be sorted by swapping adjacent elements of opposite parity
Given an array A of size n, the task is to check if the array can be sorted in increasing order, if the only operation allowed is swapping the adjacent elements if they are of opposite parity. The operation can be done any number of times. Examples: Input : n = 4, A = [1, 6, 51, 16]Output: YESExplanation: Since 51 is odd and 16 is even, we will jus
9 min read
Maximize remainder of sum of a pair of array elements with different parity modulo K
Given an array arr[] of size N, consisting of N / 2 even and odd integers each, and an integer K, the task is to find the maximum remainder of sum of a pair of array elements of different parity modulo K. Examples: Input: arr[] = {3, 2, 4, 11, 6, 7}, K = 7Output: 6Explanation: Sum of a pair of array elements = 2 + 11Sum % K = 13 % 7 = 6.Therefore,
7 min read
Article Tags :
Practice Tags :