Skip to content

Commit 116ad1a

Browse files
committed
Add solution #1246
1 parent 0faee22 commit 116ad1a

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1156,6 +1156,7 @@
11561156
1243|[Array Transformation](./solutions/1243-array-transformation.js)|Easy|
11571157
1244|[Design A Leaderboard](./solutions/1244-design-a-leaderboard.js)|Medium|
11581158
1245|[Tree Diameter](./solutions/1245-tree-diameter.js)|Medium|
1159+
1246|[Palindrome Removal](./solutions/1246-palindrome-removal.js)|Hard|
11591160
1247|[Minimum Swaps to Make Strings Equal](./solutions/1247-minimum-swaps-to-make-strings-equal.js)|Medium|
11601161
1248|[Count Number of Nice Subarrays](./solutions/1248-count-number-of-nice-subarrays.js)|Medium|
11611162
1249|[Minimum Remove to Make Valid Parentheses](./solutions/1249-minimum-remove-to-make-valid-parentheses.js)|Medium|

solutions/1246-palindrome-removal.js

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* 1246. Palindrome Removal
3+
* https://leetcode.com/problems/palindrome-removal/
4+
* Difficulty: Hard
5+
*
6+
* You are given an integer array arr.
7+
*
8+
* In one move, you can select a palindromic subarray arr[i], arr[i + 1], ..., arr[j]
9+
* where i <= j, and remove that subarray from the given array. Note that after removing
10+
* a subarray, the elements on the left and on the right of that subarray move to fill
11+
* the gap left by the removal.
12+
*
13+
* Return the minimum number of moves needed to remove all numbers from the array.
14+
*/
15+
16+
/**
17+
* @param {number[]} arr
18+
* @return {number}
19+
*/
20+
var minimumMoves = function(arr) {
21+
const n = arr.length;
22+
const dp = new Array(n).fill().map(() => new Array(n).fill(Infinity));
23+
24+
for (let i = 0; i < n; i++) {
25+
dp[i][i] = 1;
26+
}
27+
28+
for (let length = 2; length <= n; length++) {
29+
for (let i = 0; i <= n - length; i++) {
30+
const j = i + length - 1;
31+
32+
if (arr[i] === arr[j]) {
33+
if (length === 2) {
34+
dp[i][j] = 1;
35+
} else {
36+
dp[i][j] = dp[i + 1][j - 1];
37+
}
38+
}
39+
40+
for (let k = i; k < j; k++) {
41+
dp[i][j] = Math.min(dp[i][j], dp[i][k] + dp[k + 1][j]);
42+
}
43+
}
44+
}
45+
46+
return dp[0][n - 1];
47+
};

0 commit comments

Comments
 (0)