Problem 564616 · medium · Phase 05 Advanced Algorithms & Graphs

Retyping With Price Tags

dynamic programming · string DP · edit operations

A label printer can fix a misprinted label src into the intended label dst with three operations, each with its own price: insert one character (ins_cost), delete one character (del_cost), or replace one character with a different one (sub_cost). Return the cheapest total price of turning src into dst.

Examples

Input:  src = "lamp", dst = "clam", ins_cost = 2, del_cost = 3, sub_cost = 4
Output: 5
Explanation: insert "c" at the front (2) and delete the final "p" (3).

Input:  src = "ab", dst = "ba", ins_cost = 1, del_cost = 1, sub_cost = 5
Output: 2
Explanation: delete the leading "a" and insert an "a" at the end; two replacements would cost 10.

Constraints

  • 0 <= len(src), len(dst) <= 300
  • lowercase letters only
  • 1 <= ins_cost, del_cost, sub_cost <= 100
  • Target complexity: O(len(src) * len(dst)).

Goals

  • Generalise a two-string table to arbitrary operation costs
  • Initialise the empty-prefix row and column with the right multiples
Starting Python…