forked from sachinsingh3232/Hactoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLongest Ideal Subsequence
32 lines (31 loc) · 972 Bytes
/
Longest Ideal Subsequence
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
class Solution {
public int longestIdealString(String s, int k) {
int m1 = s.length();
HashMap<Character,Integer>map2 = new HashMap<>();
int []dp1 = new int [m1];
dp1[0] =1 ;
int answer = 0;
map2.put(s.charAt(0),0);
for(int i =1;i<s.length();i++)
{
char ch = s.charAt(i);
int maximum = 0;
for(int j =k;j>=0;j--)
{
if(map2.containsKey((char)(ch-j)))
{
maximum = Math.max(dp1[map2.get((char)(ch-j))] ,maximum);
}
if(map2.containsKey((char)(ch+j)))
{
maximum = Math.max(dp1[map2.get((char)(ch+j))] ,maximum);
}
}
map2.put(ch,i);
dp1[i] = maximum+1;
answer = Math.max(answer,dp1[i]);
}
answer = Math.max(answer,dp1[m1-1]);
return answer;
}
}