Maximum count of adjacent pairs with even sum in given Circular Array
Given a circular binary array arr[] of N integers, the task is to find the maximum count of pairs of adjacent elements whose sum is even where each element can belong to at most one pair.
Example:
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: arr[] = {1, 1, 1, 0, 1}
Output: 2
Explanation: Two pairs can be formed as follows:
- arr[0] and arr[4] forms the first pair, as the given array is circular and arr[0] + arr[4] = 2.
- arr[1] and arr[2] forms the second pair.
Input: arr[] = {1, 1, 1, 0, 1, 1, 0, 0}
Output: 3
Approach: The given problem can be solved using a greedy approach. It can be observed that the required pairs can be formed of the same elements only i.e, either (0, 0) or (1, 1). Also, the number of pairs that can be formed from X consecutive 1’s or 0’s is floor(X / 2). Hence traverse the given array and calculate all the possible sets of consecutive integers and add X / 2 for each set into the answer.
Also, check if both the 1st set and the last set of consecutive integers have the same value and the number of elements in both sets is odd, then increment the answer by 1.
Below is the implementation of the above approach:
Java
// Java program for the above approachimport java.io.*; class GFG { // Function to find maximum count of // pairs of adjacent elements with even // sum in the given circular array public static void findMaximumPairs(int[] arr) { // Stores the value of current // integer during traversal int currentElement = arr[0], count = 1; // First chain's count and total number // of pairs is initially 0 int firstChainCount = 0, totalPairs = 0; // flag is used to check if the current // chain is the first chain in array boolean flag = true; for (int i = 1; i < arr.length; i++) { // Count the number of // consecutive elements if (arr[i] == currentElement) { count++; } else { if (flag == true) { // Stores the count of // elements in 1st set firstChainCount = count; flag = false; } // Update answer totalPairs = totalPairs + count / 2; // Update current integer currentElement = arr[i]; count = 1; } } totalPairs = totalPairs + count / 2; int lastChainCount = count; if (arr[0] == arr[arr.length - 1] && firstChainCount % 2 == 1 && lastChainCount % 2 == 1) totalPairs++; // Print Answer System.out.println(totalPairs); } // Driver Code public static void main(String[] args) { int arr[] = { 1, 1, 1, 0, 1, 1, 0, 0 }; findMaximumPairs(arr); }} |
3
Time Complexity: O(N)
Auxiliary Space: O(1)

