Skip to content

Commit

Permalink
Added codes for 23 May
Browse files Browse the repository at this point in the history
  • Loading branch information
Tanmay-312 committed May 23, 2024
1 parent 047ce0a commit c74906f
Show file tree
Hide file tree
Showing 4 changed files with 87 additions and 0 deletions.
51 changes: 51 additions & 0 deletions GeeksForGeeks/May/23-5-24/GFG.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
//{ Driver Code Starts
// Initial Template for Java

import java.io.*;
import java.util.*;

class GFG {
public static void main(String args[]) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(in.readLine());
while (t-- > 0) {
String input_line[] = in.readLine().trim().split("\\s+");
int n = Integer.parseInt(input_line[0]);
int k = Integer.parseInt(input_line[1]);
String str = in.readLine();

Solution ob = new Solution();
System.out.println(ob.kPalindrome(str, n, k));
}
}
}
// } Driver Code Ends


class Solution
{
public int kPalindrome(String str, int n, int k)
{
// code here
int[][] dp = new int[n][n];

for (int i = 0; i < n; i++)
dp[i][i] = 1;

for (int len = 2; len <= n; len++)
{
for (int i = 0; i <= n - len; i++)
{
int j = i + len - 1;
if (str.charAt(i) == str.charAt(j))
dp[i][j] = dp[i + 1][j - 1] + 2;
else
dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]);
}
}

int lpsLength = dp[0][n - 1];

return (n - lpsLength <= k) ? 1 : 0;
}
}
2 changes: 2 additions & 0 deletions GeeksForGeeks/May/23-5-24/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Time complexity - O(n^2)
Space complexity - O(n^2)
2 changes: 2 additions & 0 deletions LeetCode/May/23-5-24/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Time complexity - O(n*logn + k)
Space complexity - O(n+k)
32 changes: 32 additions & 0 deletions LeetCode/May/23-5-24/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
class Solution
{
public int beautifulSubsets(int[] nums, int k)
{
int kMaxNum = 1000;
int[] count = new int[kMaxNum + 1];
Map<Integer, Set<Integer>> modToSubset = new HashMap<>();

for (int num : nums)
{
++count[num];
modToSubset.putIfAbsent(num % k, new TreeSet<>());
modToSubset.get(num % k).add(num);
}

int prevNum = -k;
int skip = 0;
int pick = 0;

for (Set<Integer> subset : modToSubset.values())
for (int num : subset)
{
int nonEmptyCount = (int) Math.pow(2, count[num]) - 1;
int cacheSkip = skip;
skip += pick;
pick = nonEmptyCount * (1 + cacheSkip + (num - prevNum == k ? 0 : pick));
prevNum = num;
}

return skip + pick;
}
}

0 comments on commit c74906f

Please sign in to comment.