Delete Columns to Make Sorted III

hard dynamic programming LIS string

Problem

You are given an array of n strings strs, all of the same length. You may delete any set of columns (a column is the set of characters at one index across every string). After deleting, every remaining row strs[i] must be in non-decreasing alphabetical order. Return the minimum number of columns you must delete.

Inputstrs = ["babca", "bbazb"]
Output3
Keep columns 0 and 4 ("ba" and "bb" — both rows sorted). 5 columns − 2 kept = 3 deleted.

def min_deletion_size(strs):
    w = len(strs[0])
    dp = [1] * w
    for j in range(w):
        for i in range(j):
            if all(s[i] <= s[j] for s in strs):
                dp[j] = max(dp[j], dp[i] + 1)
    return w - max(dp)
function minDeletionSize(strs) {
  const w = strs[0].length;
  const dp = new Array(w).fill(1);
  for (let j = 0; j < w; j++) {
    for (let i = 0; i < j; i++) {
      if (strs.every(s => s[i] <= s[j])) {
        dp[j] = Math.max(dp[j], dp[i] + 1);
      }
    }
  }
  return w - Math.max(...dp);
}
class Solution {
    public int minDeletionSize(String[] strs) {
        int w = strs[0].length();
        int[] dp = new int[w];
        java.util.Arrays.fill(dp, 1);
        int best = 1;
        for (int j = 0; j < w; j++) {
            for (int i = 0; i < j; i++) {
                boolean ok = true;
                for (String s : strs)
                    if (s.charAt(i) > s.charAt(j)) { ok = false; break; }
                if (ok) dp[j] = Math.max(dp[j], dp[i] + 1);
            }
            best = Math.max(best, dp[j]);
        }
        return w - best;
    }
}
int minDeletionSize(vector<string>& strs) {
    int w = strs[0].size();
    vector<int> dp(w, 1);
    int best = 1;
    for (int j = 0; j < w; j++) {
        for (int i = 0; i < j; i++) {
            bool ok = true;
            for (auto& s : strs)
                if (s[i] > s[j]) { ok = false; break; }
            if (ok) dp[j] = max(dp[j], dp[i] + 1);
        }
        best = max(best, dp[j]);
    }
    return w - best;
}
Time: O(n · w²) Space: O(w)