Maximum Product of Word Lengths in C++

C++Server Side ProgrammingProgramming

Suppose we have a string array called words, find the maximum value of length(word[i]) * length(word[j]) where the two words will not share the common letters. We can assume that each word will contain only lower case letters. If no such two words exist, then return 0. So if the input is like [“abcw”, “baz”, “foo”, “bar”, “xtfn”, “abcdef”], then the output will be 16, as two words can be “abcw”, “xtfn”.

To solve this, we will follow these steps −

  • Define a method called getRev(), this will take x as input

  • ret := 0

  • for i in range 0 to 25

    • if x / (2^i) is even, then ret := ret OR 2^i

  • return ret

  • From the main method, do the following −

  • Create one map m n := size of words array

  • for i in range 0 to n – 1

    • s := words[i], key := 0

    • for j in range 0 to size of s

      • key := key OR 2^(s[j] – ASCII of ‘a’)
    • m[i] := key

  • ret := 0

  • for i in range 0 to size of words - 1

    • for j in range i + 1 size of words – 1

      • if m[i] AND m[j] = 0, then ret := max of size of word[i] * size of word[j]

  • return ret

Example(C++)

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h&g;
using namespace std;
class Solution {
   public:
   int getRev(int x){
      int ret = 0;
      for(int i = 0; i <= 25 ; i++){
         if(!((x >> i) & 1)){
            ret |= (1 << i);
         }
      }
      return ret;
   }
   int maxProduct(vector<string>& words) {
      unordered_map <int, int> m;
      int n = words.size();
      for(int i = 0; i < n; i++){
         string s = words[i];
         int key = 0;
         for(int j = 0; j < s.size(); j++){
            key |= 1 << (s[j] - 'a');
         }
         m[i] = key;
      }
      int ret = 0;
      for(int i = 0; i < words.size(); i++){
         for(int j = i + 1; j < words.size(); j++){
            if((m[i] & m[j]) == 0){
               //cout << i << " " << j << endl;
               ret = max(ret, (int)words[i].size() * (int)words[j].size());
            }
         }
      }
      return ret;
   }
};
main(){
   Solution ob;
   vector<string> v = {"abcw","baz","foo","bar","xtfn","abcdef"};
   cout << (ob.maxProduct(v));
}

Input

["abcw","baz","foo","bar","xtfn","abcdef"]

Output

16
raja
Published on 02-May-2020 07:48:18
Advertisements