Skip to content

Practice Minimum Cost to Convert String II

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Hard#2977
LeetCode Problem

Minimum Cost to Convert String II

Problem Statement

source and target have the same length. Rule i replaces a substring equal to original[i] by changed[i] at cost[i]. You may apply rules repeatedly, but any two operation intervals must be identical or disjoint; partial overlap is forbidden. Thus multiple replacements may chain over the same interval. Return the minimum total cost to obtain target, or -1 if impossible. Duplicate rules may occur.

Source: Minimum Cost to Convert String II on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
source = "abcd", target = "acbe", original = ["a","b","c","c","e","d"], changed = ["b","c","b","e","b","e"], cost = [2,5,5,1,2,20]
Output
28

# Example 2

Input
source = "abcdefgh", target = "acdeeghh", original = ["bcd","fgh","thh"], changed = ["cde","thh","ghh"], cost = [1,3,5]
Output
9

# Example 3

Input
source = "abcdefgh", target = "addddddd", original = ["bcd","defgh"], changed = ["ddd","ddddd"], cost = [100,1578]
Output
-1

Constraints

1 <= source.length == target.length <= 1000
source, target consist only of lowercase English characters.
1 <= cost.length == original.length == changed.length <= 100
1 <= original[i].length == changed[i].length <= source.length
original[i], changed[i] consist only of lowercase English characters.
original[i] != changed[i]
1 <= cost[i] <= 10^6

Related LeetCode Problems

Practice more problems similar to Minimum Cost to Convert String II.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.