Find the largest multiple of 2, 3 and 5 in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array arr[] of size N consisting of single digits only. Our task is to find the largest multiple of 2, 3 and 5.

Let's take an example to understand the problem,

Input : arr[] = {1, 0, 5, 2}
Output : 510

Explanation

The number 510 is divisible by all 2, 3, 5.

Solution Approach

A simple solution to the problem is by checking for basic divisibility of the number created.

So, if the number needs to be divisible by 2 and 5 i.e. it is divisible by 10. For creating a number divisible by 10, the array must have zero.

If it has a zero then, we will create the largest possible number with zero at the end which is divisible by 3.

The method is shown here. Largest Multiple of Three in C++

Example

Program to illustrate the working of our solution

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   string largestMultipleOfThree(vector<int>& digits) { 
      vector<vector<int>> d(3);
      int sum = 0;
      for (int i = 0; i < digits.size(); i++) {
         int x = digits[i];
         d[x % 3].push_back(digits[i]);
         sum += x;
         sum %= 3;
      }
      if (sum) {
         if (!d[sum].size()) {
            int rem = 3 - sum;
            if (d[rem].size() < 2)
            return ""; 
            d[rem].pop_back();
            d[rem].pop_back();
         }
         else {
            d[sum].pop_back();
         }
      }
      string ret = "";
      for (int i = 0; i < 3; i++) {
         for (int j = 0; j < d[i].size(); j++) {
            ret += to_string(d[i][j]);
         }
      }
      sort(ret.begin(), ret.end(), greater<int>());
      if (ret.size() && ret[0] == '0')
      return "0";
      return ret;
   }
};
int main(){ 
   Solution ob;
   vector<int> v = {7, 2, 0, 8};
   sort(v.begin(), v.end(), greater<int>()); 
   if(v[v.size() - 1 ] != 0){
      cout<<"Not Possible!";
   }
   else{
      cout<<"The largest number is "<<(ob.largestMultipleOfThree(v));
   }
}

Output

The largest number is 870
raja
Updated on 28-Jan-2022 11:06:27

Advertisements