Construct String with Minimum Cost (Easy) - Problem
You are given a string target, an array of strings words, and an integer array costs, both arrays of the same length.
Imagine an empty string s.
You can perform the following operation any number of times (including zero):
- Choose an index
iin the range[0, words.length - 1]. - Append
words[i]tos. - The cost of operation is
costs[i].
Return the minimum cost to make s equal to target. If it's not possible, return -1.
Input & Output
Example 1 — Basic Case
$
Input:
target = "abcdef", words = ["abdef","abc","d","def","ef"], costs = [100,1,1,10,5]
›
Output:
7
💡 Note:
The minimum cost is achieved by: "abc" (cost 1) + "d" (cost 1) + "ef" (cost 5) = 7
Example 2 — Impossible Case
$
Input:
target = "aaaa", words = ["z","zz","zzz"], costs = [1,10,100]
›
Output:
-1
💡 Note:
It's impossible to construct "aaaa" using words that only contain 'z'
Example 3 — Single Word Match
$
Input:
target = "abc", words = ["abc"], costs = [5]
›
Output:
5
💡 Note:
Use the single word "abc" with cost 5 to match the entire target
Constraints
- 1 ≤ target.length ≤ 5 × 104
- 1 ≤ words.length ≤ 1000
- 1 ≤ words[i].length ≤ 5 × 104
- 1 ≤ costs[i] ≤ 104
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code