Find the largest multiple of 3 from array of digits - Set 2 in C++

C++Server Side ProgrammingProgramming

Suppose we have an array of different digits; we have to find the largest multiple of 3 that can be generated by concatenating some of the given digits in that array in any order. The answer may be very large so make it as string. If there is no answer return an empty string.

So, if the input is like [7,2,8], then the output will be 87.

To solve this, we will follow these steps −

  • Define one 2D array d, there will be three rows

  • sort the array digits

  • sum := 0

  • for initialize i := 0, when i < size of digits, update (increase i by 1), do −

    • x := digits[i]

    • insert digits[i] at the end of d[x mod 3]

    • sum := sum + x

    • sum := sum mod 3

  • if sum is non-zero, then −

    • if not size of d[sum], then −

      • rem := 3 - sum

      • if size of d[rem] < 2, then −

        • return empty string

      • delete last element from d[rem] twice

    • Otherwise

      • delete last element from d[sum]

  • ret := empty string

  • for initialize i := 0, when i < 3, update (increase i by 1), do −

    • for initialize j := 0, when j < size of d[i], update (increase j by 1), do −

      • ret := ret concatenate d[i, j] as string

  • sort the array ret

  • if size of ret and ret[0] is same as '0', then −

    • return "0"

  • return ret

Example 

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   string largestMultipleOfThree(vector<int>& digits) {
      vector<vector<int>> d(3);
      sort(digits.begin(), digits.end(), greater<int>());
      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;
   }
};
main(){
   Solution ob;
   vector<int> v = {7,2,8};
   cout << (ob.largestMultipleOfThree(v));
}

Input

{7,2,8}

Output

87
raja
Updated on 20-Aug-2020 07:28:27

Advertisements