Skip to content

960. Delete Columns to Make Sorted III 👍

  • Time: $O(k^2 \cdot n)$, where $k = |\texttt{A[0]}|$
  • Space: $O(k)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  int minDeletionSize(vector<string>& strs) {
    const int k = strs[0].length();
    // dp[i] the length of LIS ending in strs[*][i]
    vector<int> dp(k, 1);

    for (int i = 1; i < k; ++i)
      for (int j = 0; j < i; ++j)
        if (ranges::all_of(strs, [&](const string& s) { return s[j] <= s[i]; }))
          dp[i] = max(dp[i], dp[j] + 1);

    return k - ranges::max(dp);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
  public int minDeletionSize(String[] strs) {
    final int k = strs[0].length();
    // dp[i] the length of LIS ending in strs[*][i]
    int[] dp = new int[k];
    Arrays.fill(dp, 1);

    for (int i = 1; i < k; ++i)
      for (int j = 0; j < i; ++j)
        if (isSorted(strs, j, i))
          dp[i] = Math.max(dp[i], dp[j] + 1);

    return k - Arrays.stream(dp).max().getAsInt();
  }

  private boolean isSorted(String[] strs, int j, int i) {
    for (final String s : strs)
      if (s.charAt(j) > s.charAt(i))
        return false;
    return true;
  }
}