Problems was to calculate maximum product of word lengths:
Given a string array words, find the maximum value of
length(word[i]) * length(word[j])
where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0.Given ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"] Return 16 The two words can be "abcw", "xtfn". Example 2: Given ["a", "ab", "abc", "d", "cd", "bcd", "abcd"] Return 4 The two words can be "ab", "cd". Example 3: Given ["a", "aa", "aaa", "aaaa"] Return 0
My answer is correct and passed all the test cases. I am looking to get some code review on this.
class Solution(object):
def maxProduct(self, words):
"""
maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters
>> maxProduct(["eae", "ea", "aaf", "bda", "fcf", "dc", "ac", "ce", "cefde", "dabae"])
>> 15
"""
max_product = 0
words = sorted(words, key=len, reverse=True)
for index, j in enumerate(words):
for i in words[index + 1:]:
count = 0
for k in i:
if k in j:
count = 1
break
if not count:
m = len(j)
n = len(i)
word_product = m * n
if ((m == n) or (m > n and n == m - 1)) and word_product > max_product:
return word_product
if word_product > max_product:
max_product = word_product
return max_product