LeetCode Solutions

960. Delete Columns to Make Sorted III

Time: $O(n^2 \cdot |\texttt{A}|)$, where $n = |\texttt{A[0]}|$

Space: $O(|\texttt{A}|)$

			

class Solution {
 public:
  int minDeletionSize(vector<string>& A) {
    const int n = A[0].length();
    // dp[i] := LIS ending at A[*][i]
    vector<int> dp(n, 1);

    for (int i = 1; i < n; ++i)
      for (int j = 0; j < i; ++j)
        if (all_of(begin(A), end(A),
                   [&](const string& a) { return a[j] <= a[i]; }))
          dp[i] = max(dp[i], dp[j] + 1);

    return n - *max_element(begin(dp), end(dp));
  }
};
			

class Solution {
  public int minDeletionSize(String[] A) {
    final int n = A[0].length();
    // dp[i] := LIS ending at A[*][i]
    int[] dp = new int[n];
    Arrays.fill(dp, 1);

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

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

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