# Minimum count of groups such that sum of adjacent elements is divisible by K in each group

Minimum count of groups such that sum of adjacent elements is divisible by K in each groupGiven an array arr[] consisting of N integers, and an integer K, the task is to print the minimum count of groups formed by taking elements of the array such that the sum of adjacent elements is divisible by K in each group.Examples:Input: arr[] = {2, 6, 5, 8, 2, 9}, K = 2Output: 2The array can be split into two groups {2, 6, 2, 8} and {5, 9}.The sum of adjacent elements of each group is divisible by K.Thus, the minimum number of groups that can be formed is 2.Input: arr[] = {1, 1, 4, 4, 8, 6, 7}, K = 8Output: 4Explanation:The array can be split into 4 groups: {1, 7, 1}, {4, 4}, {8}, and {6}.The sum of adjacent elements of each group is divisible by K.Thus, the minimum number of groups that can be formed is 4.Input: arr[] = {144}, K = 5Output: 1Approach: The given problem can be solved based on the following observations: It can be observed that a group should be formed as:Groups should consist of only one element which is not divisible by K.All elements of the groups should be individually divisible by K.Every adjacent element of the group should be satisfied; X % K + Y % K = K, where X and Y are two adjacent elements of the group.Follow the steps below to solve the problem:Initialize a map, say mp, to store the count of arr[i] % K.Initialize a variable, say ans as 0, to store the count of groups.Traverse the array arr[] and increment the count of arr[i] % K in the mp and if arr[i] % K is 0 then assign 1 to ans.Iterate over the range [1, K / 2] and perform the following operations:Store the minimum of mp[i] and mp[K – i] in a variable, say C1.Store the maximum of mp[i] and mp[K – i] in a variable, say C2.If C1 is 0 then increment ans by C2.Otherwise, if C1 is either equal to C1 or C1 + 1, then increment ans by 1.Otherwise, increment ans by C2 – C1 – 1.Finally, after completing the above steps, print the answer obtained in ans.Below is the implementation of the above approach:C++#include using namespace std;  int findMinGroups(int arr[], int N, int K){        unordered_map mp;          int ans = 0;          for (int i = 0; i < N; i++) {                  arr[i] = arr[i] % K;                  if (arr[i] == 0) {                          ans = 1;        }        else {                          mp[arr[i]]++;        }    }          for (int i = 1; i 