├── .gitignore ├── 0-1 Knapsack ├── KnapsackUsingRecursion.java ├── README.md ├── Variations of 0-1 Knapsack │ ├── Equal_sum_partition_knapsack.java │ ├── Knapsack.java │ ├── README.md │ ├── SubsetSum.java │ ├── decoding-messages.java │ ├── minimum-no-of-jumps.java │ ├── minimum-sum-partition.java │ └── subset-sum-equals-k.java └── knapsackUsingMemoization.java ├── LICENSE ├── LIS-WITH-A-DIFFERENCE ├── abc.class └── abc.java ├── LONGEST-FIBONACCI-SEQUENCE └── abc.java ├── Longest Common Subsequence ├── LCS.java ├── LCS_Recursive_Approach.java ├── README.md ├── Variations of LCS │ ├── LongestCommonSubstring.java │ ├── Minimum-Deletions-To-Make-Palindrome.java │ ├── README.md │ ├── longestPalindromicSubsequence.java │ ├── minimumNumberOfInsertionsDeletions.java │ └── shortestCommonSupersequence.java └── lcsUsingMemoization.java ├── Longest Palindromic Substring └── longestPalindromicSubstring.java ├── MAXIMUM-SUM-INCREASING-SUBSEQUENCE ├── abc.class └── abc.java ├── Matrix Chain Multiplication ├── MCM-using-BottomUp(DP).java ├── MCM-using-Memoization.java ├── Matrix-Chain-Multiplication-using-Recursion.java └── Variations of MCM │ ├── Boolean-Parenthesization-using-Memoization.java │ ├── Brackets-in-MCM-using-BottomUp(DP).java │ ├── Egg-Dropping-Puzzle-using-Memoization.java │ ├── Egg-Dropping-Puzzle-using-Recursion.java │ ├── Palindrome-Partitioning-Optimized-Memoization.java │ ├── Palindrome-Partitioning-using-Recursion.java │ └── min-max-value-of-expression.cpp ├── Min_sum_partition ├── PARTITION-ARRAY-INTO-SUBSET-OF-EQUAL-SUM └── abc.java ├── README.md ├── Special_Keyboard_DP.java ├── Unbounded Knapsack Variation ├── Coin_change_max_number_of_ways.java └── Rod_cutting__unbounded_knapsack.java ├── coin_change_problem.java ├── count of distinct elements in every sub-array.py ├── egg_dropping_puzzle ├── find duplicate within the given range.py ├── longest substring containing all distinct.py ├── longest substring with k distinct.py ├── longest_increasing_subsequence.py ├── min_sum_partition.java ├── minimize-height-of-towers.java ├── minimumCostPath.java ├── minimumOperations.java ├── nQueen.java ├── next_larger_element.py ├── no_of_islands.py └── permutation of string.py /.gitignore: -------------------------------------------------------------------------------- 1 | /0-1 Knapsack/Variations of 0-1 Knapsack/equal_sum_partition_knapsack/build/ 2 | /0-1 Knapsack/Variations of 0-1 Knapsack/equal_sum_partition_knapsack/nbproject/private/ 3 | /0-1 Knapsack/Variations of 0-1 Knapsack/knapsack/build/ 4 | /0-1 Knapsack/Variations of 0-1 Knapsack/knapsack/nbproject/private/ -------------------------------------------------------------------------------- /0-1 Knapsack/KnapsackUsingRecursion.java: -------------------------------------------------------------------------------- 1 | /* 2 | Approach : Use Recursion 3 | A simple solution is to consider all subsets of items and calculate 4 | the total weight and value of all subsets. Consider the only subsets 5 | whose total weight is smaller than W. From all such subsets, pick 6 | the maximum value subset. 7 | 8 | Case 1: The item is included in the optimal subset. 9 | Case 2: The item is not included in the optimal set. 10 | */ 11 | 12 | import java.lang.*; 13 | import java.io.*; 14 | class main 15 | { 16 | static int sack(int wt[],int val[],int cap,int n) 17 | { 18 | if(n==0 || cap==0)//base case 19 | return 0; 20 | // Return the maximum of two cases: 21 | // (1) nth item included 22 | // (2) not included 23 | if(wt[n-1]<=cap) 24 | return Math.max(val[n-1]+sack(wt,val,cap-wt[n-1],n-1),sack(wt,val,cap,n-1)); 25 | // If weight of the nth item is 26 | // more than Knapsack capacity W, 27 | // then this item cannot be included 28 | // in the optimal solution 29 | else if(wt[n-1]>cap) 30 | return sack(wt,val,cap,n-1); 31 | return 0; 32 | } 33 | public static void main (String[] args) 34 | { 35 | 36 | Scanner sc=new Scanner(System.in); 37 | int t=sc.nextInt(); 38 | while(t-- > 0) 39 | { 40 | int n=sc.nextInt(); 41 | int cap=sc.nextInt(); 42 | int val[]=new int[n]; 43 | int wt[]=new int[n]; 44 | for(int i=0;ib) 7 | return a; 8 | else 9 | return b; 10 | } 11 | static int max_profit(int value[],int wt[],int W ,int n) 12 | { 13 | int t[][]=new int[n+1][W+1]; 14 | for(int i=0;i 1 7 | 'B' -> 2 8 | ... 9 | 'Z' -> 26 10 | You are an FBI agent. You have to determine the total number of ways that message can be decoded. 11 | Note: An empty digit sequence is considered to have one decoding. It may be assumed that the input contains valid digits 12 | from 0 to 9 and If there are leading 0’s, extra trailing 0’s and two or more consecutive 0’s then it is an invalid string. 13 | 14 | Example : 15 | Given encoded message "123", it could be decoded as "ABC" (1 2 3) or "LC" (12 3) or "AW"(1 23). 16 | So total ways are 3. 17 | 18 | Input: 19 | First line contains the test cases T. 1<=T<=1000 20 | Each test case have two lines 21 | First is length of string N. 1<=N<=40 22 | Second line is string S of digits from '0' to '9' of N length. 23 | 24 | Example: 25 | Input: 26 | 2 27 | 3 28 | 123 29 | 4 30 | 2563 31 | Output: 32 | 3 33 | 2 34 | 35 | Note : Foe detailed explanation of solution, watch here : https://www.youtube.com/watch?time_continue=525&v=Km4iqih6WjI&feature=emb_logo */ 36 | 37 | 38 | import java.util.Scanner; 39 | public class Decode_Ways { 40 | 41 | public static void main(String[] args) { 42 | // TODO Auto-generated method stub 43 | Scanner sc = new Scanner(System.in); 44 | int t = sc.nextInt(); 45 | while(t-- > 0){ 46 | int n = sc.nextInt(); 47 | String str = sc.next(); 48 | System.out.println(numDecodings(str)); 49 | } 50 | } 51 | 52 | // Time Complexity - O(n) , Space Complexity - O(1) 53 | public static int numDecodings(String s) { 54 | int first = 1; 55 | int second = s.charAt(0) == '0' ? 0 : 1; 56 | for (int i = 2; i <= s.length(); i++) { 57 | int ans = 0; 58 | int onedigit = Integer.parseInt(s.substring(i - 1, i)); 59 | int twodigit = Integer.parseInt(s.substring(i - 2, i)); 60 | if (onedigit >= 1) { 61 | ans += second; 62 | } 63 | if (twodigit >= 10 && twodigit <= 26) { 64 | ans += first; 65 | } 66 | first = second; 67 | second = ans; 68 | } 69 | return second; 70 | } 71 | 72 | // Time Complexity - O(n) , Space Complexity - O(n) 73 | public static int numDecoding(String s) { 74 | int[] dp = new int[s.length() + 1]; 75 | dp[0] = 1; 76 | dp[1] = s.charAt(0) == '0' ? 0 : 1; 77 | for (int i = 2; i <= s.length(); i++) { 78 | int onedigit = Integer.parseInt(s.substring(i - 1, i)); 79 | int twodigit = Integer.parseInt(s.substring(i - 2, i)); 80 | if (onedigit >= 1) { 81 | dp[i] += dp[i - 1]; 82 | } 83 | if (twodigit >= 10 && twodigit <= 26) { 84 | dp[i] += dp[i - 2]; 85 | } 86 | } 87 | return dp[s.length()]; 88 | } 89 | 90 | } 91 | -------------------------------------------------------------------------------- /0-1 Knapsack/Variations of 0-1 Knapsack/minimum-no-of-jumps.java: -------------------------------------------------------------------------------- 1 | /* 2 | Minimum number of jumps 3 | 4 | Given an array of integers where each element represents the max number of steps that can be made 5 | forward from that element. The task is to find the minimum number of jumps to reach the end of the 6 | array (starting from the first element). If an element is 0, then cannot move through that element. 7 | 8 | Input: 9 | The first line contains an integer T, depicting total number of test cases. Then following T lines contains 10 | a number n denoting the size of the array. Next line contains the sequence of integers a1, a2, ..., an. 11 | 12 | Output: 13 | For each testcase, in a new line, print the minimum number of jumps. If answer is not possible print "-1"(without quotes). 14 | 15 | Constraints: 16 | 1 ≤ T ≤ 100 17 | 1 ≤ N ≤ 107 18 | 0 <= ai <= 107 19 | */ 20 | 21 | import java.util.*; 22 | import java.lang.*; 23 | import java.io.*; 24 | 25 | 26 | class Main { 27 | public static void main (String[] args) throws Exception { 28 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 29 | int t = Integer.parseInt(br.readLine()); 30 | while(t-->0) 31 | { 32 | int n = Integer.parseInt(br.readLine()); 33 | String s[] = br.readLine().split(" "); 34 | int a[] = new int[n]; 35 | for(int i=0;i=i) 54 | { //Take the min of current stored value & jumps req to 55 | //reach i from j by getting jumps req to reach j plus 1. 56 | //(Plus 1 because since we have enough jumps to reach 1 from j we 57 | //simply add 1 by taking the jumps required to reach j.) 58 | jumps[i] = Math.min(jumps[i],jumps[j]+1); 59 | } 60 | } 61 | } 62 | 63 | //If first element has zero jumps in store or if the final jumps value 64 | //becomes MAX value because there's an element in between which gives zero 65 | //jumps. 66 | if(a[0]==0 || jumps[n-1] == Integer.MAX_VALUE ) 67 | System.out.println("-1"); 68 | 69 | else System.out.println(jumps[n-1]); 70 | } 71 | } -------------------------------------------------------------------------------- /0-1 Knapsack/Variations of 0-1 Knapsack/minimum-sum-partition.java: -------------------------------------------------------------------------------- 1 | /* 2 | Minimum sum partition 3 | 4 | Given an array, the task is to divide it into two sets S1 and S2 5 | such that the absolute difference between their sums is minimum. 6 | 7 | Input: 8 | The first line contains an integer 'T' denoting the total number of 9 | test cases. In each test cases, the first line contains an integer 10 | 'N' denoting the size of array. The second line contains N space- 11 | separated integers A1, A2, ..., AN denoting the elements of the array. 12 | 13 | 14 | Output: 15 | In each seperate line print minimum absolute difference. 16 | 17 | 18 | Constraints: 19 | 1<=T<=200 20 | 1<=N<=50 21 | 1<=A[i]<=200 22 | */ 23 | 24 | import java.util.*; 25 | import java.lang.*; 26 | import java.io.*; 27 | class Main 28 | { 29 | public static void main (String[] args) 30 | { 31 | Scanner sc=new Scanner(System.in); 32 | int t=sc.nextInt(); 33 | while(t-->0) 34 | { 35 | int n=sc.nextInt(); 36 | int arr[]=new int[n]; 37 | int sum=0; 38 | for(int i=0;isum) 43 | dp[index][sum]= subsetSum(index-1,sum,arr,dp); 44 | else{ 45 | if(arr[index]==sum) 46 | dp[index][sum]=1+subsetSum(index-1,sum,arr,dp); 47 | else 48 | dp[index][sum]= subsetSum(index-1,sum-arr[index],arr,dp)+ subsetSum(index-1,sum,arr,dp); 49 | } 50 | return(dp[index][sum]); 51 | } 52 | } -------------------------------------------------------------------------------- /0-1 Knapsack/knapsackUsingMemoization.java: -------------------------------------------------------------------------------- 1 | /* 2 | Problem Statement: Given weights and values of n items, put these items in a knapsack of 3 | capacity cap to get the maximum total value in the knapsack. In other words, given two 4 | integer arrays val[0..n-1] and wt[0..n-1] which represent values and weights associated 5 | with n items respectively. Also given an integer W which represents knapsack capacity, 6 | find out the maximum value subset of val[] such that sum of the weights of this subset 7 | is smaller than or equal to W. You cannot break an item, either pick the complete item 8 | or don’t pick it (0-1 property). 9 | 10 | Approach : Recursion with Memoization 11 | 12 | This method is basically an extension to the recursive approach so that we can overcome 13 | the problem of calculating redundant cases and thus increased complexity. We can solve 14 | this problem by simply creating a 2-D array that can store a particular state (n, w) if 15 | we get it the first time. Now if we come across the same state (n, w) again instead of 16 | calculating it in exponential complexity we can directly return its result stored in the 17 | table in constant time. This method gives an edge over the recursive approach in this aspect. 18 | 19 | 20 | */ 21 | 22 | class main 23 | 24 | { 25 | static int sack(int wt[],int val[],int cap,int n,int dp[][]) 26 | { 27 | if(n==0 || cap==0) 28 | return 0; 29 | if(dp[n][cap] != -1) 30 | return dp[n][cap]; 31 | if(wt[n-1]<=cap) 32 | dp[n][cap]=Math.max(val[n-1]+sack(wt,val,cap-wt[n-1],n-1,dp),sack(wt,val,cap,n-1,dp)); 33 | else if(wt[n-1]>cap) 34 | dp[n][cap]=sack(wt,val,cap,n-1,dp); 35 | return dp[n][cap]; 36 | 37 | } 38 | public static void main (String[] args) throws IOException 39 | { 40 | 41 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 42 | int t = Integer.parseInt(br.readLine()); 43 | while(t-- > 0) 44 | { 45 | int n=Integer.parseInt(br.readLine()); 46 | int cap=Integer.parseInt(br.readLine()); 47 | int val[]=new int[n]; 48 | int wt[]=new int[n]; 49 | String line[] = br.readLine().split(" "); 50 | for(int i=0;i hm=new HashMap<>(); 15 | int res=Integer.MIN_VALUE; 16 | for(int i:a) 17 | { 18 | int temp=hm.getOrDefault(i-diff, 0)+1; 19 | res=Math.max(res,temp); 20 | hm.put(i,temp); 21 | } 22 | System.out.println(res); 23 | } 24 | } -------------------------------------------------------------------------------- /LONGEST-FIBONACCI-SEQUENCE/abc.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class abc 3 | { 4 | public static void main(String[] args) { 5 | int n; 6 | Scanner sc=new Scanner(System.in); 7 | n=sc.nextInt(); 8 | int a[]=new int[n]; 9 | HashMap index=new HashMap<>(); 10 | for(int i=0;i len=new HashMap<>(); 16 | int res=0; 17 | for(int i=0;i=0 && k=3?res:0); 31 | 32 | } 33 | } -------------------------------------------------------------------------------- /Longest Common Subsequence/LCS.java: -------------------------------------------------------------------------------- 1 | ?// Length of Longest Common Subsequence 2 | 3 | class Solution { 4 | public int longestCommonSubsequence(String text1, String text2) { 5 | 6 | 7 | char x[]=text1.toCharArray(); 8 | char y[]=text2.toCharArray(); 9 | int n=x.length; 10 | int m=y.length; 11 | int t[][]=new int[n+1][m+1]; 12 | return lcs(x,y,n,m,t); 13 | 14 | } 15 | public int lcs(char x[],char y[],int n,int m,int t[][]){ 16 | 17 | for(int i=0;i 0) 24 | { 25 | int n=sc.nextInt(); 26 | int m=sc.nextInt(); 27 | String s1=sc.next(); 28 | String s2=sc.next(); 29 | char x[]=s1.toCharArray(); 30 | char y[]=s2.toCharArray(); 31 | int t[][]=new int[n+1][m+1]; 32 | int r=0; 33 | for(int i=0;i 0) 30 | { 31 | String s=sc.next(); 32 | StringBuilder sb=new StringBuilder(); 33 | sb.append(s); 34 | sb=sb.reverse();//reverse the string 35 | char x[]=s.toCharArray(); 36 | char[] y = new char[sb.length()]; 37 | sb.getChars(0, sb.length(), y, 0); 38 | int n=x.length; 39 | int m=y.length; 40 | int t[][]=new int[n+1][m+1]; 41 | for(int i=0;i 0) 31 | { 32 | int n=sc.nextInt(); 33 | int m=sc.nextInt(); 34 | String s1=sc.next(); 35 | String s2=sc.next(); 36 | char x[]=s1.toCharArray(); 37 | char y[]=s2.toCharArray(); 38 | 39 | int t[][]=new int[n+1][m+1]; 40 | for(int i=0;i 0) 36 | { 37 | String s1=sc.next(); 38 | String s2=sc.next(); 39 | char x[]=s1.toCharArray(); 40 | char y[]=s2.toCharArray(); 41 | int n=x.length; 42 | int m=y.length; 43 | int t[][]=new int[n+1][m+1]; 44 | for(int i=0;ilast-first) 30 | { 31 | first=i-((len-1)/2); 32 | last=i+(len/2); 33 | } 34 | } 35 | return s.substring(first,last+1); 36 | } 37 | public int expand(String s,int l,int r) 38 | { 39 | if(s==null || l>r) 40 | return 0; 41 | while(l>=0 && r 0){ 38 | int n = scan.nextInt(); 39 | int arr[] = new int[n]; 40 | for(int i=0;i 0) 19 | { 20 | int n=sc.nextInt(); 21 | int a[]=new int[n]; 22 | for(int i=0;i 0) 38 | { 39 | int n=sc.nextInt(); 40 | int a[]=new int[n]; 41 | for(int i=0;i true 9 | 'F' ---> false 10 | 11 | And following operators filled between symbols 12 | 13 | Operators 14 | & ---> boolean AND 15 | | ---> boolean OR 16 | ^ ---> boolean XOR 17 | 18 | Count the number of ways we can parenthesize the expression so that the value of expression evaluates to true. 19 | 20 | For Example: 21 | The expression is "T | T & F ^ T", it evaluates true 22 | in 4 ways ((T|T)&(F^T)), (T|(T&(F^T))), (((T|T)&F)^T) 23 | and (T|((T&F)^T)). 24 | 25 | Return No_of_ways Mod 1003. 26 | 27 | Input: 28 | First line contains the test cases T. 1<=T<=500 29 | Each test case have two lines 30 | First is length of string N. 1<=N<=100 31 | Second line is string S (boolean expression). 32 | Output: 33 | No of ways Mod 1003. 34 | 35 | 36 | Example: 37 | Input: 38 | 2 39 | 7 40 | T|T&F^T 41 | 5 42 | T^F|F 43 | 44 | Output: 45 | 4 46 | 2 */ 47 | 48 | 49 | 50 | import java.util.*; 51 | import java.lang.*; 52 | import java.io.*; 53 | 54 | class GFG { 55 | 56 | public static char[] s; 57 | public static Map hm = new HashMap(); 58 | 59 | public static void main (String[] args) throws IOException{ 60 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 61 | int t = Integer.parseInt(br.readLine()); 62 | while(t!=0){ 63 | int n = Integer.parseInt(br.readLine()); 64 | String str = br.readLine().trim(); 65 | s = str.toCharArray(); 66 | System.out.println(solve(0,n-1,true)); 67 | hm.clear(); 68 | t--; 69 | } 70 | } 71 | public static int solve(int i, int j, boolean isTrue){ 72 | int ans = 0; 73 | if(i>j) 74 | return 0; 75 | if(i==j){ 76 | if(isTrue==true) 77 | return (s[i]=='T')?1:0; 78 | else 79 | return (s[i]=='F')?1:0; 80 | } 81 | String temp = Integer.toString(i) + " " + Integer.toString(j) + " " + Boolean.toString(isTrue); 82 | for (Map.Entry set : hm.entrySet()) { 83 | if(set.getKey().equals(temp)) 84 | return set.getValue(); 85 | } 86 | for(int k=i+1; k<=j-1; k+=2){ 87 | int lt = solve(i,k-1,true); 88 | int lf = solve(i,k-1,false); 89 | int rt = solve(k+1,j,true); 90 | int rf = solve(k+1,j,false); 91 | if(s[k]=='&'){ 92 | if(isTrue==true) 93 | ans+=(lt*rt); 94 | else 95 | ans+=(lf*rt)+(lt*rf)+(lf*rf); 96 | }else if(s[k]=='|'){ 97 | if(isTrue==true) 98 | ans+=(lt*rt)+(lt*rf)+(lf*rt); 99 | else 100 | ans+=(lf*rf); 101 | }else{ 102 | if(isTrue==true) 103 | ans+=(lf*rt)+(lt*rf); 104 | else 105 | ans+=(lt*rt)+(lf*rf); 106 | } 107 | } 108 | hm.put(temp,ans%1003); 109 | return ans%1003; 110 | } 111 | } -------------------------------------------------------------------------------- /Matrix Chain Multiplication/Variations of MCM/Brackets-in-MCM-using-BottomUp(DP).java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Brackets in Matrix Chain Multiplication 4 | 5 | Given a sequence of matrices, find the most efficient way to multiply these matrices together. The problem is not actually 6 | to perform the multiplications, but merely to decide in which order to perform the multiplications. There are many options 7 | to multiply a chain of matrices because matrix multiplication is associative i.e. no matter how one parenthesize the product, 8 | the result will be the same. 9 | 10 | Example: 11 | if you had four matrices A, B, C, and D, you would have: 12 | 13 | (ABC)D = (AB)(CD) = A(BCD) = .... 14 | However, the order in which one parenthesize the product affects the number 15 | of simple arithmetic operations needed to compute the product, or the efficiency. 16 | 17 | For example: 18 | 19 | A: 10 × 30 matrix 20 | B : 30 × 5 matrix 21 | C : 5 × 60 matrix 22 | Then, 23 | (AB)C = (10×30×5) + (10×5×60) 24 | = 1500 + 3000 25 | = 4500 operations 26 | A(BC) = (30×5×60) + (10×30×60) 27 | = 9000 + 18000 28 | = 27000 operations. 29 | Given an array arr[] which represents the chain of matrices such that the ith matrix Ai is of dimension arr[i-1] x arr[i]. 30 | Your task is to write a program that should print the optimal way to multiply the matrix chain such that minimum number of 31 | multiplications operations are needed to multiply the chain. Represent first matrix as starting Alphabet of the english 32 | dictionary i.e. 'A', and the rest so on. 33 | 34 | Input: p[] = {40, 20, 30, 10, 30} 35 | Output: Optimal parenthesization is ((A(BC))D) 36 | There are 4 matrices of dimensions 40x20, 37 | 20x30, 30x10 and 10x30. Let the input 4 38 | matrices be A, B, C and D. The minimum 39 | number of multiplications are obtained 40 | by putting parenthesis in following way 41 | (A(BC))D --> 20*30*10 + 40*20*10 + 40*10*30 42 | 43 | Input: p[] = {10, 20, 30, 40, 30} 44 | Output: Optimal parenthesization is (((AB)C)D) 45 | There are 4 matrices of dimensions 10x20, 46 | 20x30, 30x40 and 40x30. Let the input 4 47 | matrices be A, B, C and D. The minimum 48 | number of multiplications are obtained by 49 | putting parenthesis in following way 50 | ((AB)C)D --> 10*20*30 + 10*30*40 + 10*40*30 51 | 52 | Input: 53 | The first line of the input contains an integer T, denoting the number of test cases. Then T test case follows. 54 | The first line of each test case contains an integer N, denoting the number of elements in the array. 55 | Then next line contains N space separated integers denoting the values of the element in the array. 56 | 57 | Output: 58 | For each test case the print the minimum number of operations needed to multiply the chain. 59 | 60 | Constraints: 61 | 1<=T<=100 62 | 2<=N<=27 63 | 1<=A[]<=500 64 | 65 | Example: 66 | Input: 67 | 2 68 | 5 69 | 1 2 3 4 5 70 | 3 71 | 3 3 3 72 | Output: 73 | (((AB)C)D) 74 | (AB) 75 | 76 | */ 77 | 78 | /*package whatever //do not write package name here */ 79 | 80 | import java.util.*; 81 | import java.lang.*; 82 | import java.io.*; 83 | 84 | class GFG { 85 | static int ind=65; 86 | static void print(int i,int j,int dp[][]){ 87 | if(i==j){ 88 | System.out.print((char)ind++); 89 | return; 90 | } 91 | System.out.print("("); 92 | print(i,dp[j][i],dp); 93 | print(dp[j][i]+1,j,dp); 94 | System.out.print(")"); 95 | } 96 | public static void main (String[] args)throws IOException { 97 | BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 98 | int t=Integer.parseInt(br.readLine()); 99 | while(t-->0){ 100 | int n=Integer.parseInt(br.readLine()); 101 | String s[]=br.readLine().split("\\s+"); 102 | int p[]=new int[n]; 103 | for(int i=0;i 0) 37 | { 38 | int e=sc.nextInt(); 39 | int f=sc.nextInt(); 40 | int t[][]=new int[e+1][f+1];//lookup table 41 | for(int row[]:t) 42 | Arrays.fill(row,-1);//Intialize elements by -1 43 | System.out.println(solve(e,f,t)); 44 | } 45 | } 46 | public static int solve(int e,int f,int t[][]) 47 | { 48 | if(f==0 || f==1) 49 | return f; 50 | if(e==1) 51 | return f; 52 | if(t[e][f]!=-1)//if already present don't call the recursive function 53 | return t[e][f]; 54 | else 55 | { 56 | int min=Integer.MAX_VALUE; 57 | for(int k=1;k<=f;k++) 58 | { 59 | int temp=1+Math.max(solve(e-1,k-1,t),solve(e,f-k,t)); 60 | min=Math.min(min,temp); 61 | t[e][f]=min; 62 | } 63 | } 64 | return t[e][f]; 65 | } 66 | } -------------------------------------------------------------------------------- /Matrix Chain Multiplication/Variations of MCM/Egg-Dropping-Puzzle-using-Recursion.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | class main 5 | { 6 | public static void main (String[] args) 7 | { 8 | //code 9 | Scanner sc=new Scanner(System.in); 10 | int test=sc.nextInt(); 11 | while(test-- > 0) 12 | { 13 | int e=sc.nextInt(); 14 | int f=sc.nextInt(); 15 | System.out.println(solve(e,f)); 16 | } 17 | } 18 | public static int solve(int e,int f) 19 | { 20 | if(f==0 || f==1) 21 | return f; 22 | if(e==1) 23 | return f; 24 | int min=Integer.MAX_VALUE; 25 | for(int k=1;k<=f;k++) 26 | { 27 | int temp=1+Math.max(solve(e-1,k-1),solve(e,f-k)); 28 | min=Math.min(min,temp); 29 | } 30 | return min; 31 | } 32 | } -------------------------------------------------------------------------------- /Matrix Chain Multiplication/Variations of MCM/Palindrome-Partitioning-Optimized-Memoization.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | class main 5 | { 6 | public static void main (String[] args) 7 | { 8 | Scanner sc=new Scanner(System.in); 9 | int test=sc.nextInt(); 10 | while(test-->0) 11 | { 12 | String s=sc.next(); 13 | int n=s.length(); 14 | int t[][]=new int[n+1][n+1]; 15 | for(int row[]:t) 16 | Arrays.fill(row,-1);//Intialize elements by -1 17 | System.out.println(solve(s,0,n-1,t)); 18 | } 19 | } 20 | public static boolean palindrome(String s,int i,int j) 21 | { 22 | while (i <= j) { 23 | if (s.charAt(i++) != s.charAt(j--)) { 24 | return false; 25 | } 26 | } 27 | return true; 28 | } 29 | public static int solve(String s,int i,int j,int t[][]) 30 | { 31 | if(i==j||palindrome(s,i,j)) 32 | return 0; 33 | int ans=Integer.MAX_VALUE; 34 | int left=0,right=0; 35 | if(t[i][j]!=-1) 36 | return t[i][j]; 37 | else 38 | { 39 | for(int k=i;k<=j-1;k++) 40 | { 41 | 42 | if(t[i][k]!=-1) 43 | left=t[i][k]; 44 | else 45 | { 46 | left=solve(s,i,k,t); 47 | t[i][k]=left; 48 | } 49 | if(t[k+1][j]!=-1) 50 | right=t[k+1][j]; 51 | else 52 | { 53 | right=solve(s,k+1,j,t); 54 | t[k+1][j]=right; 55 | } 56 | int temp=1+left+right; 57 | if(temp0) 36 | { 37 | String s=sc.next(); 38 | int n=s.length(); 39 | System.out.println(solve(s,0,n-1)); 40 | } 41 | } 42 | public static boolean palindrome(String s,int i,int j) 43 | { 44 | while (i <= j)//check palindrome 45 | { 46 | if (s.charAt(i++) != s.charAt(j--)) { 47 | return false; 48 | } 49 | } 50 | return true; 51 | } 52 | public static int solve(String s,int i,int j) 53 | { 54 | if(i==j||palindrome(s,i,j))//base condition 55 | return 0; 56 | int ans=Integer.MAX_VALUE; 57 | for(int k=i;k<=j-1;k++) 58 | { 59 | int temp=solve(s,i,k)+solve(s,k+1,j)+1; 60 | if(temp 23 | using namespace std; 24 | 25 | // Utility method to check whether a character 26 | // is operator or not 27 | bool isOperator(char op) 28 | { 29 | return (op == '+' || op == '*'); 30 | } 31 | 32 | // method prints minimum and maximum value 33 | // obtainable from an expression 34 | void printMinAndMaxValueOfExp(string exp) 35 | { 36 | vector num; 37 | vector opr; 38 | string tmp = ""; 39 | 40 | // store operator and numbers in different vectors 41 | for (int i = 0; i < exp.length(); i++) 42 | { 43 | if (isOperator(exp[i])) 44 | { 45 | opr.push_back(exp[i]); 46 | num.push_back(atoi(tmp.c_str())); 47 | tmp = ""; 48 | } 49 | else 50 | { 51 | tmp += exp[i]; 52 | } 53 | } 54 | // storing last number in vector 55 | num.push_back(atoi(tmp.c_str())); 56 | 57 | int len = num.size(); 58 | int minVal[len][len]; 59 | int maxVal[len][len]; 60 | 61 | // initializing minval and maxval 2D array 62 | for (int i = 0; i < len; i++) 63 | { 64 | for (int j = 0; j < len; j++) 65 | { 66 | minVal[i][j] = INT_MAX; 67 | maxVal[i][j] = 0; 68 | 69 | // initializing main diagonal by num values 70 | if (i == j) 71 | minVal[i][j] = maxVal[i][j] = num[i]; 72 | } 73 | } 74 | 75 | // looping similar to matrix chain multiplication 76 | // and updating both 2D arrays 77 | for (int L = 2; L <= len; L++) 78 | { 79 | for (int i = 0; i < len - L + 1; i++) 80 | { 81 | int j = i + L - 1; 82 | for (int k = i; k < j; k++) 83 | { 84 | int minTmp = 0, maxTmp = 0; 85 | 86 | // if current operator is '+', updating tmp 87 | // variable by addition 88 | if(opr[k] == '+') 89 | { 90 | minTmp = minVal[i][k] + minVal[k + 1][j]; 91 | maxTmp = maxVal[i][k] + maxVal[k + 1][j]; 92 | } 93 | 94 | // if current operator is '*', updating tmp 95 | // variable by multiplication 96 | else if(opr[k] == '*') 97 | { 98 | minTmp = minVal[i][k] * minVal[k + 1][j]; 99 | maxTmp = maxVal[i][k] * maxVal[k + 1][j]; 100 | } 101 | 102 | // updating array values by tmp variables 103 | if (minTmp < minVal[i][j]) 104 | minVal[i][j] = minTmp; 105 | if (maxTmp > maxVal[i][j]) 106 | maxVal[i][j] = maxTmp; 107 | } 108 | } 109 | } 110 | 111 | // last element of first row will store the result 112 | cout << "Minimum value : " << minVal[0][len - 1] 113 | << ", Maximum value : " << maxVal[0][len - 1]; 114 | } 115 | 116 | // Driver code to test above methods 117 | int main() 118 | { 119 | string expression = "1+2*3+4*5"; 120 | printMinAndMaxValueOfExp(expression); 121 | return 0; 122 | } 123 | -------------------------------------------------------------------------------- /Min_sum_partition: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | import java.lang.*; 4 | import java.io.*; 5 | 6 | class GFG { 7 | public static void main (String[] args) { 8 | //code 9 | Scanner o=new Scanner(System.in); 10 | int t=o.nextInt(); 11 | for(int i=0;i list=subset(arr,n,range); 25 | int min=Integer.MAX_VALUE; 26 | for(int i=0;i subset(int arr[],int n, int sum){ 34 | boolean dp[][]=new boolean[n+1][sum+1]; 35 | for(int i=0;i<=sum;i++){ 36 | dp[0][i]=false; 37 | } 38 | 39 | for(int i=0;i<=n;i++){ 40 | dp[i][0]=true; 41 | } 42 | 43 | for(int i=1;i<=n;i++){ 44 | for(int j=1;j<=sum;j++){ 45 | if(arr[i-1]<=j){ 46 | dp[i][j]=dp[i-1][j-arr[i-1]] || dp[i-1][j]; 47 | } 48 | else{ 49 | dp[i][j]=dp[i-1][j]; 50 | } 51 | } 52 | } 53 | 54 | ArrayList l=new ArrayList<>(); 55 | for(int j=0;j<=sum/2;j++){ 56 | if(dp[n][j]){ 57 | l.add(j); 58 | } 59 | } 60 | 61 | return l; 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /PARTITION-ARRAY-INTO-SUBSET-OF-EQUAL-SUM/abc.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class abc 3 | { 4 | static boolean check(int[] nums,int n) 5 | { 6 | int sum=0; 7 | for(int i:nums) 8 | { 9 | sum+=i; 10 | } 11 | if(sum%2!=0) return false; 12 | boolean dp[][]=new boolean[sum/2+1][n+1]; 13 | for(int i=0;i<=n;i++) 14 | { 15 | dp[0][i]=true; 16 | } 17 | for(int i=1;i<=sum/2;i++) 18 | { 19 | dp[i][0]=false; 20 | } 21 | for(int i=1;i<=sum/2;i++) 22 | { 23 | for(int j=1;j<=n;j++) 24 | { 25 | dp[i][j]=dp[i][j-1]; 26 | if(nums[j-1]<=i) 27 | dp[i][j]=dp[i][j] || dp[i-nums[j-1]][j-1]; 28 | } 29 | } 30 | return dp[sum/2][n]; 31 | } 32 | public static void main(String[] args) { 33 | int n; 34 | Scanner sc=new Scanner(System.in); 35 | n=sc.nextInt(); 36 | int a[]=new int[n]; 37 | for(int i=0;i= 1; b--) { 21 | int curr = (n - b - 1) * screen[b - 1]; 22 | if (curr > screen[n - 1]) 23 | screen[n - 1] = curr; 24 | } 25 | } 26 | return screen[N - 1]; 27 | } 28 | 29 | public static void main (String[] args) throws IOException { 30 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 31 | int t = Integer.parseInt(br.readLine().trim()); 32 | while(t-->0){ 33 | String inputLine[] = br.readLine().trim().split(" "); 34 | int n = Integer.parseInt(inputLine[0]); 35 | System.out.println(findoptimal(n)); 36 | } 37 | } 38 | } 39 | 40 | /* 41 | 42 | For Input: 43 | 3 44 | 45 | your output is: 46 | 3 47 | execution time .15sec 48 | */ 49 | -------------------------------------------------------------------------------- /Unbounded Knapsack Variation/Coin_change_max_number_of_ways.java: -------------------------------------------------------------------------------- 1 | // 2 | //package coin_change_max_number_of_ways; 3 | public class Coin_change_max_number_of_ways { 4 | 5 | static int ways(int arr[],int p,int n) 6 | { 7 | int t[][]=new int[n+1][p+1]; 8 | for(int i=0;ib) 8 | return a; 9 | else 10 | return b; 11 | } 12 | static int max_profit(int length[],int price[],int L ,int n) 13 | { 14 | int t[][]=new int[n+1][L+1]; 15 | for(int i=0;i0) 36 | {int m = sc.nextInt(); 37 | int arr[] =new int[m]; 38 | for(int i=0;i=k-1: 10 | print('The count of distinct element in sub-array',[start,i],len(d)) 11 | d[s[start]]-=1 12 | if d[s[start]]==0: 13 | del d[s[start]] 14 | start+=1 15 | 16 | # 2 1 2 3 2 1 4 5 17 | # 5 18 | -------------------------------------------------------------------------------- /egg_dropping_puzzle: -------------------------------------------------------------------------------- 1 | #code 2 | INT_MAX = 32767 3 | def eggDrop(n, k): 4 | # A 2D table where entery eggFloor[i][j] will represent minimum 5 | # number of trials needed for i eggs and j floors. 6 | eggFloor = [[0 for x in range(k + 1)] for x in range(n + 1)] 7 | 8 | # We need one trial for one floor and0 trials for 0 floors 9 | for i in range(1, n + 1): 10 | eggFloor[i][1] = 1 11 | eggFloor[i][0] = 0 12 | 13 | # We always need j trials for one egg and j floors. 14 | for j in range(1, k + 1): 15 | eggFloor[1][j] = j 16 | 17 | # Fill rest of the entries in table using optimal substructure 18 | # property 19 | for i in range(2, n + 1): 20 | for j in range(2, k + 1): 21 | eggFloor[i][j] = INT_MAX 22 | for x in range(1, j + 1): 23 | res = 1 + max(eggFloor[i-1][x-1], eggFloor[i][j-x]) 24 | if res < eggFloor[i][j]: 25 | eggFloor[i][j] = res 26 | 27 | # eggFloor[n][k] holds the result 28 | return eggFloor[n][k] 29 | for _ in range(int(input())): 30 | n,k=input().split() 31 | n=int(n) 32 | k=int(k) 33 | print(eggDrop(n, k)) 34 | -------------------------------------------------------------------------------- /find duplicate within the given range.py: -------------------------------------------------------------------------------- 1 | arr = list(map(int,input().split())) 2 | k = int(input()) 3 | start=0 4 | s= set() 5 | f= False 6 | for i in range(len(arr)): 7 | 8 | if i>=k: 9 | if arr[i] in s: 10 | print('Duplicate found') 11 | f = True 12 | break 13 | s.remove(arr[start]) 14 | start+=1 15 | s.add(arr[i]) 16 | if not f: 17 | print('Not found') 18 | 19 | -------------------------------------------------------------------------------- /longest substring containing all distinct.py: -------------------------------------------------------------------------------- 1 | s = input() 2 | d ={} 3 | start =0 4 | res ='' 5 | for i in range(len(s)): 6 | d[s[i]] = d.get(s[i],0)+1 7 | while d[s[i]]>1: 8 | d[s[start]]-=1 9 | start+=1 10 | l = i-start+1 11 | if l> len(res): 12 | res = s[start:i+1] 13 | print(res) 14 | 15 | # abbcdafeegh 16 | 17 | -------------------------------------------------------------------------------- /longest substring with k distinct.py: -------------------------------------------------------------------------------- 1 | s = input() 2 | k = int(input()) 3 | 4 | def rec(k): 5 | d= {} 6 | start =0 7 | 8 | res ='' 9 | for i in range(len(s)): 10 | d[s[i]] = d.get(s[i],0)+1 11 | 12 | while len(d)>k: 13 | d[s[start]]-=1 14 | if d[s[start]] ==0: 15 | del d[s[start]] 16 | start+=1 17 | l = i - start+1 18 | if l > len(res): 19 | res = s[start:i+1] 20 | return res 21 | 22 | print(rec(k)) 23 | 24 | -------------------------------------------------------------------------------- /longest_increasing_subsequence.py: -------------------------------------------------------------------------------- 1 | #code 2 | def lis(arr): 3 | n = len(arr) 4 | lis = [1]*n 5 | for i in range (1 , n): 6 | for j in range(0 , i): 7 | if arr[i] > arr[j] and lis[i]< lis[j] + 1 : 8 | lis[i] = lis[j]+1 9 | maximum = 0 10 | for i in range(n): 11 | maximum = max(maximum , lis[i]) 12 | return maximum 13 | for _ in range(int(input())): 14 | n=int(input()) 15 | a=list(map(int,input().strip().split())) 16 | print(lis(a)) 17 | -------------------------------------------------------------------------------- /min_sum_partition.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | import java.lang.*; 4 | import java.io.*; 5 | 6 | class GFG { 7 | static int findMinRec(int arr[], int n) 8 | { 9 | // Calculate sum of all elements 10 | int sum = 0; 11 | for (int i = 0; i < n; i++) 12 | sum += arr[i]; 13 | 14 | // Create an array to store 15 | // results of subproblems 16 | boolean dp[][] = new boolean[n + 1][sum + 1]; 17 | 18 | // Initialize first column as true. 19 | // 0 sum is possible with all elements. 20 | for (int i = 0; i <= n; i++) 21 | dp[i][0] = true; 22 | 23 | // Initialize top row, except dp[0][0], 24 | // as false. With 0 elements, no other 25 | // sum except 0 is possible 26 | for (int i = 1; i <= sum; i++) 27 | dp[0][i] = false; 28 | 29 | // Fill the partition table 30 | // in bottom up manner 31 | for (int i = 1; i <= n; i++) 32 | { 33 | for (int j = 1; j <= sum; j++) 34 | { 35 | // If i'th element is excluded 36 | dp[i][j] = dp[i - 1][j]; 37 | 38 | // If i'th element is included 39 | if (arr[i - 1] <= j) 40 | dp[i][j] =dp[i][j] || dp[i - 1][j - arr[i - 1]]; 41 | } 42 | } 43 | 44 | // Initialize difference of two sums. 45 | int diff = Integer.MAX_VALUE; 46 | 47 | // Find the largest j such that dp[n][j] 48 | // is true where j loops from sum/2 t0 0 49 | for (int j = sum / 2; j >= 0; j--) 50 | { 51 | // Find the 52 | if (dp[n][j] == true) 53 | { 54 | diff = sum - 2 * j; 55 | break; 56 | } 57 | } 58 | return diff; 59 | } 60 | 61 | public static void main (String[] args) { 62 | //code 63 | 64 | Scanner sc=new Scanner(System.in); 65 | int t=sc.nextInt(); 66 | while(t-->0) 67 | { 68 | int n=sc.nextInt(); 69 | int arr[]=new int[n]; 70 | // int sum=0; 71 | for(int i=0;i0) 42 | { 43 | int k = sc.nextInt(); 44 | int n = sc.nextInt(); 45 | int arr[] = new int[n]; 46 | for(int i=0;ik){ 51 | for(int i=0;i=0 && j>=0; i--,j--) 21 | if(arr[i][j]==1) 22 | return false; 23 | for(i=r, j=c; i=0; i++,j--) 24 | if(arr[i][j]==1) 25 | return false; 26 | return true; 27 | } 28 | 29 | public static boolean placeQueen(int arr[][],int c) 30 | { 31 | int i; 32 | if(c>=n) 33 | return true; 34 | for(i=0;i0 and stack[-1]=len(k)-1: 14 | 15 | if d==h: 16 | print('Anagram',s[start:i+1],'present at index',start) 17 | h[s[start]]-=1 18 | if h[s[start]]==0: 19 | del h[s[start]] 20 | start+=1 21 | 22 | # XYYZXZYZXXYZ 23 | # XYZ 24 | 25 | 26 | 27 | 28 | --------------------------------------------------------------------------------