dp
with dimensions n x n
, where n
is the length of the input array arr
, and fill it with the maximum number of moves (initially n
).dp[i][i]
to 1 for all i
, since a single element is always a palindrome and can be removed in one move.dp[i][i+1]
to 1 if arr[i] == arr[i+1]
, otherwise set it to 2, for all i
from 0 to n-2
.n
, do the following:
a. For each starting index i
of the subarray, calculate the ending index j
.
b. If arr[i] == arr[j]
, set dp[i][j]
to dp[i+1][j-1]
.
c. Otherwise, set dp[i][j]
to the minimum of dp[i+1][j-1] + 2
and the minimum moves required for all possible splits of the subarray.dp[0][n-1]
as the result.