1653. Minimum Deletions to Make String Balanced

Difficulty:
Related Topics:
Similar Questions:

Problem

You are given a string s consisting only of characters 'a' and 'b'​​​​.

You can delete any number of characters in s to make s balanced. s is balanced if there is no pair of indices (i,j) such that i < j and s[i] = 'b' and s[j]= 'a'.

Return **the *minimum* number of deletions needed to make s balanced**.

  Example 1:

Input: s = "aababbab"
Output: 2
Explanation: You can either:
Delete the characters at 0-indexed positions 2 and 6 ("aababbab" -> "aaabbb"), or
Delete the characters at 0-indexed positions 3 and 6 ("aababbab" -> "aabbbb").

Example 2:

Input: s = "bbaaaaabb"
Output: 2
Explanation: The only solution is to delete the first two characters.

  Constraints:

Solution

/**
 * @param {string} s
 * @return {number}
 */
var minimumDeletions = function(s) {
  var map = Array(s.length).fill(0);
  for (var i = s.length - 2; i >= 0; i--) {
    map[i] = map[i + 1] + (s[i + 1] === 'a' ? 1 : 0);
  }
  return solve(s, 0, 0, Array(s.length), map);
};

var solve = function(s, i, num, map, map2) {
    if (i >= s.length) return 0;
    if (map[i] === undefined) {
      if (s[i] === 'a') {
        map[i] = solve(s, i + 1, 0, map, map2);
      } else {
        map[i] = Math.min(
          solve(s, i + 1, 1, map, map2),
          map2[i],
        );
      }
    }
    return map[i] + num;
};

Explain:

nope.

Complexity: