Minimize Cost to Form Target String

TCS NQT Coding Medium Go Ad-Free - ₹20/mo

Given strings X and Y, and integers A and B, form the target string X by concatenating substrings taken from Y or its reverse. Each substring from Y costs A, and each from reverse(Y) costs B. Determine the minimum total cost to form X, or return -1 if it is impossible.

Examples:

Input: X = "abc", Y = "aabbcc", A = 3, B = 5

Output: 6

Explanation: Form "abc" by taking substring "ab" from Y (cost A=3) and "c" from Y (cost A=3), total cost 6.

Input: X = "xyz", Y = "zyx", A = 2, B = 4

Output: 4

Explanation: Take entire reverse(Y) "zyx" as a substring with cost B=4.

Input: X = "abc", Y = "xyz", A = 3, B = 5

Output: -1

Explanation: Impossible since no characters in X are present in Y or its reverse.

Constraints

  • 1 ≤ length of X, length of Y ≤ 10000
  • 0 ≤ A, B ≤ 1000