You are given a list of distinct words and a corresponding list of positive costs. Construct a binary search tree using all words such that its inorder traversal gives the words in lexicographical order.
If a word is placed at level L, where the root is at level 0, its contribution to the total cost is (L + 1) * cost. Return the minimum possible total cost among all valid binary search trees.
long minimumCostBST(List<String> words, List<Integer> costs)
words contains distinct lowercase words.costs contains the positive cost of each corresponding word.words.get(i) has cost costs.get(i).words does not define the binary search tree order.0.L contributes (L + 1) * cost(word) to the answer.1 ≤ words.size() ≤ 300costs.size() == words.size()1 ≤ words.get(i).length() ≤ 501 ≤ costs.get(i) ≤ 1,000,000words contains distinct lowercase English words.Input:
minimumCostBST(words = ["cat", "ant", "dog"], costs = [5, 2, 4])
Output:
17
Explanation:
In lexicographical order, the words are ["ant", "cat", "dog"]. Their corresponding costs are [2, 5, 4]. One optimal tree places "cat" at level 0, "ant" at level 1, and "dog" at level 1. The total cost is 1 * 5 + 2 * 2 + 2 * 4 = 17.
Input:
minimumCostBST(words = ["mango", "kiwi", "orange", "grape"], costs = [8, 3, 6, 2])
Output:
32
Explanation:
In lexicographical order, the words are ["grape", "kiwi", "mango", "orange"]. Their corresponding costs are [2, 3, 8, 6]. One optimal tree places "mango" at level 0, "kiwi" and "orange" at level 1, and "grape" at level 2. The total cost is 1 * 8 + 2 * 3 + 2 * 6 + 3 * 2 = 32.
Input:
minimumCostBST(words = ["a"], costs = [10])
Output:
10
Explanation:
There is only one word, so it must be the root. Its contribution is 1 * 10 = 10.