# 1246. Palindrome Removal

Given an integer array arr, in one move you can select a palindromic subarray arr[i], arr[i+1], ..., arr[j] where i <= j, and remove that subarray from the given array. Note that after removing a subarray, the elements on the left and on the right of that subarray move to fill the gap left by the removal.

Return the minimum number of moves needed to remove all numbers from the array.

Example 1:

Input: arr = [1,2]
Output: 2

Example 2:

Input: arr = [1,3,4,1,5]
Output: 3
Explanation: Remove [4] then remove [1,3,1] then remove [5].

# Solution

Approach 1: DP.

# Code (Python)

Approach 1:

    def minimumMoves(self, nums: List[int]) -> int:
        # DP. moves[i][j]: min num of steps to remove all from nums[i:j+1]
        moves = [[float('inf')] * len(nums) for _ in range(len(nums))]
        for span in range(0, len(nums)):
            for i in range(0, len(nums) - span): # i + span < len(nums)
                j = i + span
                if span == 0:
                    moves[i][j] = 1
                elif span == 1: # also a base case for 2 based palindromes
                    moves[i][j] = 1 if nums[i] == nums[j] else 2
                else:
                    if nums[i] == nums[j]:
                        moves[i][j] = moves[i+1][j-1]
                    else:
                        for mid in range(0, j):
                            moves[i][j] = min(moves[i][j], moves[i][mid] + moves[mid+1][j])
        return moves[0][-1]

# Code (C++)

Approach 1:

Approach 2: