Count of adjacent pairs in given Array with even sum
Given an array arr[] of N integers, the task is to find the count of pairs of adjacent elements whose sum is even where each element can belong to at most one pair.
Example:
Input: arr[] = {1, 12, 1, 3, 5}
Output: 1
Explanation: 1 pair can be formed with arr[3] and arr[4].
Input: arr[] = {1, 2, 3, 4, 5, 6, 8, 9}
Output: 0
Approach: The given problem can be solved using a greedy approach. It can be observed that the required pairs can be formed of the elements having same parity only i.e, either (odd, odd) or (even, even). Also, the number of pairs that can be formed from X consecutive odd or even 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.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int find_maximum_pairs(vector< int >& arr)
{
int totalPairs = 0;
for ( int i = 0; i < arr.size() - 1; i++)
{
if ((arr[i] + arr[i + 1]) % 2 == 0) {
totalPairs++;
i++;
}
}
return totalPairs;
}
int main()
{
vector< int > arr = { 1, 12, 1, 3, 5 };
cout << find_maximum_pairs(arr) << endl;
}
|
Java
import java.io.*;
class GFG {
public static int findMaximumPairs( int [] arr)
{
int totalPairs = 0 ;
for ( int i = 0 ; i < arr.length - 1 ;
i++) {
if ((arr[i] + arr[i + 1 ]) % 2 == 0 ) {
totalPairs++;
i++;
}
}
return totalPairs;
}
public static void main(String[] args)
{
int arr[] = { 1 , 12 , 1 , 3 , 5 };
System.out.println(
findMaximumPairs(arr));
}
}
|
Python3
def find_maximum_pairs(arr):
totalPairs = 0
i = 0
while i < ( len (arr) - 1 ):
if ((arr[i] + arr[i + 1 ]) % 2 = = 0 ):
totalPairs + = 1
i + = 1
i + = 1
return totalPairs
arr = [ 1 , 12 , 1 , 3 , 5 ]
print (find_maximum_pairs(arr))
|
C#
using System;
class GFG
{
public static int findMaximumPairs( int [] arr)
{
int totalPairs = 0;
for ( int i = 0; i < arr.Length - 1;
i++) {
if ((arr[i] + arr[i + 1]) % 2 == 0) {
totalPairs++;
i++;
}
}
return totalPairs;
}
public static void Main()
{
int [] arr = { 1, 12, 1, 3, 5 };
Console.Write(findMaximumPairs(arr));
}
}
|
Javascript
<script>
function findMaximumPairs(arr) {
let totalPairs = 0;
for (let i = 0; i < arr.length - 1;
i++) {
if ((arr[i] + arr[i + 1]) % 2 == 0) {
totalPairs++;
i++;
}
}
return totalPairs;
}
let arr = [1, 12, 1, 3, 5];
document.write(
findMaximumPairs(arr));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Last Updated :
17 Jan, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...