|
| 1 | +package dynamic_programming; |
| 2 | + |
| 3 | +/** |
| 4 | + * Created by gouthamvidyapradhan on 12/05/2020 Given an integer array arr, in one move you can |
| 5 | + * select a palindromic subarray arr[i], arr[i+1], ..., arr[j] where i <= j, and remove that |
| 6 | + * subarray from the given array. Note that after removing a subarray, the elements on the left and |
| 7 | + * on the right of that subarray move to fill the gap left by the removal. |
| 8 | + * |
| 9 | + * <p>Return the minimum number of moves needed to remove all numbers from the array. |
| 10 | + * |
| 11 | + * <p>Example 1: |
| 12 | + * |
| 13 | + * <p>Input: arr = [1,2] Output: 2 Example 2: |
| 14 | + * |
| 15 | + * <p>Input: arr = [1,3,4,1,5] Output: 3 Explanation: Remove [4] then remove [1,3,1] then remove |
| 16 | + * [5]. |
| 17 | + * |
| 18 | + * <p>Constraints: |
| 19 | + * |
| 20 | + * <p>1 <= arr.length <= 100 1 <= arr[i] <= 20 |
| 21 | + */ |
| 22 | +public class PalindromeRemoval { |
| 23 | + public static void main(String[] args) { |
| 24 | + int[] A = {1, 3, 1, 2, 4, 2}; |
| 25 | + System.out.println(new PalindromeRemoval().minimumMoves(A)); |
| 26 | + } |
| 27 | + |
| 28 | + int[][] DP; |
| 29 | + |
| 30 | + public int minimumMoves(int[] arr) { |
| 31 | + DP = new int[arr.length][arr.length]; |
| 32 | + return dp(0, arr.length - 1, arr); |
| 33 | + } |
| 34 | + |
| 35 | + private int dp(int i, int j, int[] arr) { |
| 36 | + if (i > j) return 1; |
| 37 | + else if (DP[i][j] != 0) return DP[i][j]; |
| 38 | + else { |
| 39 | + int min = Integer.MAX_VALUE; |
| 40 | + for (int t = j; t >= i; t--) { |
| 41 | + if (arr[i] == arr[t]) { |
| 42 | + min = Math.min(min, dp(i + 1, t - 1, arr) + ((t + 1 > j) ? 0 : dp(t + 1, j, arr))); |
| 43 | + } |
| 44 | + } |
| 45 | + DP[i][j] = min; |
| 46 | + return min; |
| 47 | + } |
| 48 | + } |
| 49 | +} |
0 commit comments