Wednesday, 27 Oct 2021

# Count the combination of 4s and/or 5s required to make each Array element 0

Given an array arr[] consisting of N positive integers, the task is to check if each array element can be represented in terms of numbers 4 and 5. If it is possible, then print the total count of 4 and 5 needed for each array element. Otherwise, print -1.Examples:Input: arr[] = {12, 11, 9}Output: 3 -1 2Explanation: arr( =12): Print 3 as it can be represented by using 3 fours i.e. 4 + 4 + 4 = 12.arr(= 11): Print -1 as it cannot be represented by any combination of 4 and 5. arr(= 9): Print 2 as it can be represented by using one 4 and one 5 i.e. 4 + 5 = 9.Input: arr[] = {7, 15, 17, 22}Output: -1 3 4 5Approach: The problem can be solved using greedy approach and a bit of mathematics. Follow the steps below to solve the problem:Initialize a vector say ans, as {-1} where the ans[i] stores the answer to a possible answer for the value arr[i] of the array arr[].Iterate over a range [0, N-1] using the variable i and perform the following steps:If arr[i] is less than 4, then, continue.Initialize two variables, say sum as INT_MAX to store the count of numbers of 4 and 5 needed to form arr[i] and cnt as 0 to keep the count of the current factor of 4.Iterate over a range [0, arr[i]] using the variable j and perform the following steps:If (arr[i] – j) is divisible by 5, then, set the value of the sum to the minimum of sum and (cnt + (arr[i] – j)/5).Increase the value of cnt by 1 and j by 4.If the sum is not equal to INT_MAX, then, set the value of ans[i] in the vector ans as sum.Finally, after completing the above steps, print the values in the vector ans.Below is the implementation of the above approach:C++#include using namespace std;  void sumOfCombinationOf4OR5(vector arr, int N){          vector ans(N, -1);          for (int i = 0; i < N; i++) {          if (arr[i] < 4) {            continue;        }                                  int sum = INT_MAX, cnt = 0;                          for (int j = 0; j