Leetcode Problem 1320. Minimum Distance to Type a Word Using Two Fingers

1320. Minimum Distance to Type a Word Using Two Fingers

Leetcode Solutions

Dynamic Programming withD Array

  1. Initialize a 1D array dp with 26 elements to 0, representing the 26 letters of the alphabet.
  2. Initialize variables res to 0 and save to 0. res will hold the total distance if typed by one finger, and save will hold the maximum distance saved by using two fingers.
  3. Iterate through the word, for each pair of adjacent characters b and c, calculate the distance d(b, c).
  4. For each character a in the alphabet, update dp[b] with the maximum of dp[b] and dp[a] + d(b, c) - d(a, c).
  5. Update save with the maximum of save and dp[b].
  6. Add d(b, c) to res.
  7. After iterating through the word, return res - save as the result.
UML Thumbnail

Dynamic Programming withD Array

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...