Skip to content

Commit 94b9e8b

Browse files
Solved Problems
1 parent 214984e commit 94b9e8b

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,7 @@ My accepted leetcode solutions to some of the common interview problems.
265265
- ![#f03c15](https://placehold.it/15/f03c15/000000?text=+) [Number of Ways to Stay in the Same Place After Some Steps](problems/src/dynamic_programming/NumberOfWaysToStayInTheSamePlace.java) (Hard)
266266
- [Toss Strange Coins](problems/src/dynamic_programming/TossStrangeCoins.java) (Medium)
267267
- [Knight Dialer](problems/src/dynamic_programming/KnightDialer.java) (Medium)
268+
- ![#f03c15](https://placehold.it/15/f03c15/000000?text=+) [Palindrome Removal](problems/src/dynamic_programming/PalindromeRemoval.java) (Hard)
268269

269270

270271
#### [Greedy](problems/src/greedy)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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

Comments
 (0)