|
| 1 | +/** |
| 2 | + * 960. Delete Columns to Make Sorted III |
| 3 | + * https://leetcode.com/problems/delete-columns-to-make-sorted-iii/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given an array of n strings strs, all of the same length. |
| 7 | + * |
| 8 | + * We may choose any deletion indices, and we delete all the characters in those indices |
| 9 | + * for each string. |
| 10 | + * |
| 11 | + * For example, if we have strs = ["abcdef","uvwxyz"] and deletion indices {0, 2, 3}, then |
| 12 | + * the final array after deletions is ["bef", "vyz"]. |
| 13 | + * |
| 14 | + * Suppose we chose a set of deletion indices answer such that after deletions, the final |
| 15 | + * array has every string (row) in lexicographic order. (i.e., |
| 16 | + * (strs[0][0] <= strs[0][1] <= ... <= strs[0][strs[0].length - 1]), |
| 17 | + * and (strs[1][0] <= strs[1][1] <= ... <= strs[1][strs[1].length - 1]), |
| 18 | + * and so on). Return the minimum possible value of answer.length. |
| 19 | + */ |
| 20 | + |
| 21 | +/** |
| 22 | + * @param {string[]} strs |
| 23 | + * @return {number} |
| 24 | + */ |
| 25 | +var minDeletionSize = function(strs) { |
| 26 | + const isValid = (input, a, b) => input.every(row => row[a] <= row[b]); |
| 27 | + const cols = strs[0].length; |
| 28 | + const dp = new Array(cols).fill(1); |
| 29 | + |
| 30 | + for (let i = 1; i < cols; i++) { |
| 31 | + for (let j = 0; j < i; j++) { |
| 32 | + if (isValid(strs, j, i)) { |
| 33 | + dp[i] = Math.max(dp[i], dp[j] + 1); |
| 34 | + } |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + return cols - Math.max(...dp); |
| 39 | +}; |
0 commit comments