-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongest_Ideal_Subsequence.java
More file actions
130 lines (113 loc) · 3.11 KB
/
Longest_Ideal_Subsequence.java
File metadata and controls
130 lines (113 loc) · 3.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
import java.util.*;
import java.io.*;
import java.lang.*;
public class Longest_Ideal_Subsequence {
class Solution {
private int solveMemo(String s, int idx, int k, int[][] dp, char ch)
{
if(idx >= s.length())
{
return 0;
}
if(dp[idx][ch] != -1)
{
return dp[idx][ch];
}
int take = 0;
int nontake = 0;
if(Math.abs(ch - s.charAt(idx)) <= k || ch == '#')
{
take = 1 + solveMemo(s, idx + 1, k, dp, s.charAt(idx));
}
nontake = solveMemo(s, idx + 1, k, dp, ch);
return dp[idx][ch] = Math.max(take, nontake);
}
public int longestIdealString(String s, int k)
{
int[][] dp = new int[s.length() + 1][130];
for (int[] d : dp)
{
Arrays.fill(d, -1);
}
return solveMemo(s, 0, k, dp, '#');
}
}
//dp Tabulation
// class Solution {
// public int longestIdealString(String s, int k)
// {
// int n = s.length();
// int[] dp = new int[n];
// int max = 0;
// for (int i = 0; i < n; i++)
// {
// dp[i] = 1;
// for (int j = 0; j < i; j++)
// {
// if (Math.abs(s.charAt(j) - s.charAt(i)) <= k)
// {
// dp[i] = Math.max(dp[i], dp[j] + 1);
// }
// }
// max = Math.max(max, dp[i]);
// }
// return max;
// }
// }
// dp Memoization
// class Solution {
// public int longestIdealString(String s, int k)
// {
// int n = s.length();
// int[][] dp = new int[n][n];
// for (int[] row : dp)
// {
// Arrays.fill(row, -1);
// }
// int a = ans(0 , -1 , s , k , dp);
// return a;
// }
// public int ans(int i , int last , String s , int k , int[][] dp)
// {
// if(i>=s.length())
// {
// return 0;
// }
// if(dp[i][last + 1] != -1)
// {
// return dp[i][last + 1];
// }
// int take = 0;
// int no_take = 0;
// if(last == -1 || Math.abs(s.charAt(last) - s.charAt(i)) <= k)
// {
// take = ans(i+1 , i , s , k , dp) + 1;
// }
// no_take = ans(i+1 , last , s , k , dp);
// return dp[i][last+1] = Math.max(take , no_take);
// }
// }
//Recurssion
// class Solution {
// public int longestIdealString(String s, int k)
// {
// int a = ans(0 , -1 , s , k);
// return a;
// }
// public int ans(int i , int last , String s , int k)
// {
// if(i>=s.length())
// {
// return 0;
// }
// int take = 0;
// int no_take = 0;
// if(last == -1 || Math.abs(s.charAt(last) - s.charAt(i)) <= k)
// {
// take = ans(i+1 , i , s , k) + 1;
// }
// no_take = ans(i+1 , last , s , k);
// return Math.max(take , no_take);
// }
// }
}