Minimum number of socks required to picked to have at least K pairs of the same color

Minimum number of socks required to picked to have at least K pairs of the same colorGiven an array arr[] consisting of N integers such that arr[i] representing the number of socks of the color i and an integer K, the task is to find the minimum number of socks required to be picked to get at least K pairs of socks of the same color.Examples:Input: arr[] = {3, 4, 5, 3}, K = 6Output: 15Explanation: One will need to pick all the socks to get at least 6 pairs of matching socks.Input: arr[] = {4, 5, 6}, K = 3Output: 8Approach: The given problem can be solved based on the following observations: According to Pigeonhole’s Principle i.e., in the worst-case scenario if N socks of different colors have been picked then the next pick will form a matching pair of socks.Suppose one has picked N socks of different colors then, for each (K – 1) pairs one will need to pick two socks, one for forming a pair and another for maintaining N socks of all different colors, and for the last pair, there is only need to pick a single sock of any color available.Therefore, the idea is to find the total number of pairs that can be formed by the same colors and if the total count is at most K then print (2*K + N – 1) as the minimum count of pairs to be picked. Otherwise, print “-1” as there are not enough socks to formed K pairs.Below is the implementation of the above approach:C++#include using namespace std;int findMin(int arr[], int N, int k){            int pairs = 0;        for (int i = 0; i < N; i++) {        pairs += arr[i] / 2;    }        if (k > pairs)        return -1;        else        return 2 * k + N – 1;}int main(){    int arr[3] = { 4, 5, 6 };    int K = 3;    cout pairs)            return -1;                else            return 2 * k + N – 1;    }        public static void main(String[] args)    {        int[] arr = { 4, 5, 6 };        int K = 3;        int N = arr.length;        System.out.println(findMin(arr, N, K));    }}Output: 8Time Complexity: O(N)Auxiliary Space: O(1)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.