forked from gouravkrosx/DSA-Revision
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDynamic Programming.txt
2142 lines (1881 loc) · 66.6 KB
/
Dynamic Programming.txt
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1) sort and array using recursion
2)DP question-> https://www.youtube.com/watch?v=VT4bZV24QNo
3)Heavy weight knapsack
4) Just add all the questions from eclipse after doing all questions
SOLUTIONS OF THESE QUESTIONS ARE EITHER ON GFG OR ON LEETCODE.
---------------------------------------DYNAMIC PROGRAMMING-----------------------------------------
1. 0-1 Knapsack / Book Shop (CSES)
public static int KnapsackTD(int[] wt, int[] price, int vidx, int cap, int[][] strg) {
// if (cap < 0) {
// return Integer.MAX_VALUE;
// }
if (vidx == wt.length) {
return 0;
}
if (strg[vidx][cap] != 0) {
return strg[vidx][cap];
}
int ans = 0;
int in = 0;
if (cap >= wt[vidx]) {
in = KnapsackTD(wt, price, vidx + 1, cap - wt[vidx], strg) + price[vidx];
}
int ex = KnapsackTD(wt, price, vidx + 1, cap, strg);
ans = Math.max(in, ex);
strg[vidx][cap] = ans;
return ans;
}
->Bottom Up Approach->https://www.youtube.com/watch?v=bUSaenttI24&list=WL&index=57&t=21s
public static int KnapsackBU(int[]wt,int[]val,int n,int cap){
int[][]dp=new int[n+1][cap+1];
for(int i=1;i<=n;i++){
for(int j=1;j<=cap;j++){
if(j>=wt[i-1]) //player can bat or weight can be added.
{ int rCap=j-wt[i-1];
if(dp[i-1][rCap]+val[i-1]>dp[i-1][j]){
dp[i][j]=dp[i-1][rCap]+val[i-1]; //took i-1 in val array also bcz of the storage, draw matrix to know
}else{
dp[i][j]=dp[i-1][j];
}
}else{
dp[i][j]=dp[i-1][j]; //player can't bat or weight can't be added
}
}
}
return dp[n][cap];
}
----------------- -------------------------------------------------------------------------------
2. Matrix Chain Multiplication
public static int MCMTD(int[] matrix, int si, int ei, int[][] strg) {
if (ei - si == 1) {
return 0;
}
if (strg[si][ei] != 0) {
return strg[si][ei];
}
int ans = Integer.MAX_VALUE;
for (int k = si + 1; k <= ei - 1; k++) {
int fp = MCMTD(matrix, si, k, strg);
int sp = MCMTD(matrix, k, ei, strg);
int sw = matrix[si] * matrix[k] * matrix[ei];
int overall = fp + sp + sw;
if (overall < ans) {
ans = overall;
}
}
strg[si][ei] = ans;
return ans;
}
------------------------------------------------------------------------------------------------
3. Edit Distance
public int EditdistanceTD(String s1, String s2, int[][] strg) {
if (s1.length() == 0 || s2.length() == 0) {
return Math.max(s1.length(), s2.length());
}
if (strg[s1.length()][s2.length()] != -1) {
return strg[s1.length()][s2.length()];
}
char ch1 = s1.charAt(0);
char ch2 = s2.charAt(0);
String ros1 = s1.substring(1);
String ros2 = s2.substring(1);
int ans = 0;
if (ch1 == ch2) {
ans = EditdistanceTD(ros1, ros2, strg);
} else {
int ins = EditdistanceTD(ros1, s2, strg) + 1;
int del = EditdistanceTD(s1, ros2, strg) + 1;
int rep = EditdistanceTD(ros1, ros2, strg) + 1;
ans = Math.min(ins, Math.min(del, rep));
}
strg[s1.length()][s2.length()] = ans;
return ans;
}
------------------------------------------------------------------------------------------------
4. Catalan Number to find no. of Bst's
public static int Catalannumberofbsts(int n, int[] strg) {
if (n <= 1) {
return 1;
}
if (strg[n] != 0) {
return strg[n];
}
int sum = 0;
for (int i = 1; i <= n; i++) {
int left = Catalannumberofbsts(i - 1, strg);
int right = Catalannumberofbsts(n - i, strg);
int total = left * right;
sum += total;
}
strg[n] = sum;
return sum;
}
->Catalan Number
public static void CatalanNumber(int n) {
int dp[] = new int[n + 1];
dp[0] = 1;
dp[1] = 1;
for (int i = 2; i < dp.length; i++) {
for (int j = 0; j < i; j++) {
dp[i] += dp[j] * dp[i - j - 1];
}
}
System.out.println(dp[n]);
}
------------------------------------------------------------------------------------------------
5. Longest Common Subsequence
public int LCSTD(String s1, String s2, int[][] strg) {
if (s1.length() == 0 || s2.length() == 0) {
return 0;
}
if (strg[s1.length()][s2.length()] != -1) {
return strg[s1.length()][s2.length()];
}
char ch1 = s1.charAt(0);
char ch2 = s2.charAt(0);
String ros1 = s1.substring(1);
String ros2 = s2.substring(1);
int ans = 0;
if (ch1 == ch2) {
ans = LCSTD(ros1, ros2, strg) + 1;
} else {
int fp = LCSTD(s1, ros2, strg);
int sp = LCSTD(ros1, s2, strg);
ans = Math.max(fp, sp);
}
strg[s1.length()][s2.length()] = ans;
return ans;
}
*)LCS Space Optimised->
public int LCsSpaceOptimised(String s1, String s2) {
int[] strg = new int[s2.length() + 1];
int prev = 0; //for taking ros1,ros2 in acccount because we can't get this from 1d array
for (int i = s1.length() - 1; i >= 0; i--) {
prev = strg[strg.length - 1];
for (int j = strg.length - 2; j >= 0; j--) {
int backup = strg[j];
char ch1 = s1.charAt(i);
char ch2 = s2.charAt(j);
int ans = 0;
if (ch1 == ch2) {
ans = prev + 1;
} else {
int fp = strg[j + 1];
int sp = strg[j];
ans = Math.max(fp, sp);
}
prev = backup;
strg[j] = ans;
}
}
return strg[0];
}
------------------------------------------------------------------------------------------------
6. Palindromic Partitions/cuts
->BLog because we did some further optimization in this question
https://leetcode.com/problems/palindrome-partitioning-ii/discuss/1267844/JAVA-or-Recursion-%2B-Memoization-or-Optimized-Matrix-Chain-Multiplication-Approach-with-Code-(MCM)
public int PalindromicpartitionscutTD(String str, int si, int ei, int[][] strg) {
if (strg[si][ei] != -1) {
return strg[si][ei];
}
if (Ispalindrome(str, si, ei)) {
return 0;
}
int ans = Integer.MAX_VALUE;
for (int k = si; k <= ei - 1; k++) {
if (Ispalindrome(str, si, k)) {
int min = 1 + PalindromicpartitionscutTD(str, k + 1, ei, strg);
ans = Math.min(min, ans);
}
}
strg[si][ei] = ans;
return ans;
}
------------------------------------------------------------------------------------------------
7. Wildcard Matching
public boolean WildcardpatternTD(String s1, String s2, int[][] strg) {
if (s1.length() == 0 && s2.length() == 0) {
return true;
}
if (s1.length() != 0 && s2.length() == 0) {
return false;
}
if (s1.length() == 0 && s2.length() != 0) {
for (int i = 0; i < s2.length(); i++) {
if (s2.charAt(i) != '*') {
return false;
}
}
return true;
}
if (strg[s1.length()][s2.length()] != 0) {
return strg[s1.length()][s2.length()] == 2 ? true : false;
}
char ch1 = s1.charAt(0);
char ch2 = s2.charAt(0);
String ros1 = s1.substring(1);
String ros2 = s2.substring(1);
boolean ans = false;
if (ch1 == ch2 || ch2 == '?') {
ans = WildcardpatternTD(ros1, ros2, strg);
} else if (ch2 == '*') {
boolean op1 = WildcardpatternTD(s1, ros2, strg);
boolean op2 = WildcardpatternTD(ros1, s2, strg);
ans = op1 || op2;
}
strg[s1.length()][s2.length()] = (ans) ? 2 : 1;
return ans;
}
------------------------------------------------------------------------------------------------
8. Board Path/Dice Combination (CSES)
public static int boardpathTD(int curr, int end, int[] strg) {
if (curr == end) {
return 1;
}
if (curr > end) {
return 0;
}
if (strg[curr] != 0) {
return strg[curr];
}
int count = 0;
for (int dice = 1; dice <= 6; dice++) {
if (curr + dice <= end) {
count += boardpathTD(curr + dice, end, strg);
}
}
strg[curr] = count;
return count;
}
------------------------------------------------------------------------------------------------
9. Coin Change/ CoinCombinationII (CSES)
->Using 2 states
public long CoinCombinationII(int[] coin, int val, int n) {
long[][] dp = new long[n + 1][val + 1];
for (int i = 1; i <= n; i++) {
for (int sum = 0; sum <= val; sum++) {
if (sum == 0) {
dp[i][sum] = 1;
} else {
long op1 = (coin[i-1] > sum) ? 0 : dp[i][sum - coin[i-1]];
long op2 = (i == 1) ? 0 : dp[i - 1][sum];
dp[i][sum] = (op1 + op2);
}
}
}
return dp[n][val];
}
Using One state only->
public int CoinCombinationII(int[] coin, int val, int n) {
int[] dp = new int[val + 1];
dp[0] = 1; // if no sum then we can leave this and this could be a way
for (int i = 0; i < n; i++) {
for (int j = coin[i]; j < dp.length; j++) {
dp[j] += dp[j - coin[i]];
}
}
return dp[val];
}
CoinCombinationI (Permutation) (CSES)
public static long CoinCombinationI(int[] coin, int val, int n) {
long[] dp = new long[val + 1];
dp[0] = 1; // if no sum then we can leave and this could be a way
for (int sum = 1; sum <= val; sum++) {
for (int coin_value : coin) {
if (coin_value <= sum)
dp[sum] = (dp[sum] + dp[sum - coin_value]) % MOD;
}
}
return dp[val];
}
------------------------------------------------------------------------------------------------
10. Minimizing Coins/ Coin change on leetcode
public int coinChange(int[] coins, int amount) {
Arrays.sort(coins);
int[]dp=new int[amount+1];
Arrays.fill(dp,amount+1);
dp[0]=0;
for(int i=0;i<=amount;i++){
for(int j=0;j<coins.length;j++){
if(coins[j]<=i){
dp[i]=Math.min(dp[i],1+dp[i-coins[j]]);
}else
break;
}
}
return (dp[amount]>amount)?-1:dp[amount];
}
------------------------------------------------------------------------------------------------
11. Subset Sum Problem/ Partition Equal Subset Sum
public boolean SubsetSum(int nums[], int vidx, int sum, int total,HashMap<String,Boolean>state) {
String current=vidx+""+sum;
if (state.containsKey(current)) {
return state.get(current);
}
if (total == 2 * sum) {
return true;
}
if (sum > total || vidx >= nums.length)
return false;
boolean ans=SubsetSum(nums,vidx+1,sum+nums[vidx],total,state)||
SubsetSum(nums,vidx+1,sum,total,state);
state.put(current,ans);
return ans;
}
------------------------------------------------------------------------------------------------
12. Target Sum Subset ->(Kind of 0-1 Knapsack Problem)
https://www.pepcoding.com/resources/online-java-foundation/dynamic-programming-and-greedy/target-sum-subsets-dp-official/ojquestion
public static boolean TargetSumSubsets(int[]arr,int n,int tar){
boolean[][]dp=new boolean[n+1][tar+1];
dp[0][0]=true; //because empty set can be make sum 0 only.
for(int i=1;i<=n;i++){
for(int j=0;j<=tar;j++){
if(j==0){
dp[i][j]=true;
continue;
}
if(j<arr[i-1]){
dp[i][j]=dp[i-1][j];
}else{
boolean op1=dp[i-1][j];
boolean op2=dp[i-1][j-arr[i-1]];
dp[i][j]=op1||op2;
}
}
}
return dp[n][tar];
}
------------------------------------------------------------------------------------------------
13. Friends Pairing Problem
public static long FriendsPairing(int n) {
if (n == 0)
return 0;
if (n == 1)
return 1;
if (n == 2)
return 2;
long dp[] = new long[n + 1];
int M = 1000000007;
dp[1] = 1;
dp[2] = 2;
for (int i = 3; i < dp.length; i++) {
dp[i] = (dp[i - 1] + ((i - 1) * dp[i - 2]) % M) % M;
}
return dp[n];
}
------------------------------------------------------------------------------------------------
14. Binomial Coefficient Problem (nCr)
Formula Used-> C(n, r) = C(n-1, r-1) + C(n-1, r)
C(n, 0) = C(n, n) = 1
public static int nCr(int n, int r) {
int C[][] = new int[n + 2][r + 2];
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= Math.min(i, r); j++) {
if (j == 0 || j == i)
C[i][j] = 1;
else
C[i][j] = (C[i - 1][j] % MOD + (C[i - 1][j - 1]) % MOD) % MOD;
}
}
return C[n][r];
}
------------------------------------------------------------------------------------------------
15. Permutation Coefficient Problem (nPr)
Formula Used->P(n, k) = P(n-1, k) + k* P(n-1, k-1)
P(n,0)=1;
static int permutationCoeff(int n,
int k)
{
int P[][] = new int[n + 2][k + 2];
// Calculate value of Permutation
// Coefficient in bottom up manner
for (int i = 0; i <= n; i++)
{
for (int j = 0;
j <= Math.min(i, k);
j++)
{
// Base Cases
if (j == 0)
P[i][j] = 1;
// Calculate value using previosly
// stored values
else
P[i][j] = P[i - 1][j] +
(j * P[i - 1][j - 1]);
// This step is important
// as P(i,j)=0 for j>i
P[i][j + 1] = 0;
}
}
return P[n][k];
}
------------------------------------------------------------------------------------------------
16. Grid Paths (CSES)
public static int GridPaths(int[][] grid, int n) {
int[][] strg = new int[n + 1][n + 1];
for (int row = n; row >= 1; row--) {
for (int col = n; col >= 1; col--) {
if (grid[row - 1][col - 1] == 1) {
strg[row][col] = 0;
continue;
}
if (row == n && col == n) {
strg[row][col] = 1;
} else {
int op1 = (col == n) ? 0 : strg[row][col + 1];
int op2 = (row == n) ? 0 : strg[row + 1][col];
strg[row][col] = (op1 + op2) % MOD;
}
}
}
return strg[1][1];
}
------------------------------------------------------------------------------------------------
17. Removing Digits (CSES)
private static int RemovingDigits(int n) {
int[] dp = new int[n + 1];
for (int i = 1; i <= n; i++) {
char[] arr = new String("" + i).toCharArray();
int res = Integer.MAX_VALUE;
for (int j = 0; j < arr.length; j++) {
if (arr[j] != '0')
res = Math.min(dp[i - (arr[j] - '0')] + 1, res);
}
dp[i] = res;
}
return dp[n];
}
------------------------------------------------------------------------------------------------
18. Longest Common Subsequence 3D (with 3 Strings)
public static int LCS3(String s1, String s2, String s3, int[][][] strg) {
if (s1.length() == 0 || s2.length() == 0 || s3.length() == 0) {
return 0;
}
if (strg[s1.length()][s2.length()][s3.length()] != -1) {
return strg[s1.length()][s2.length()][s3.length()];
}
char ch1 = s1.charAt(0);
char ch2 = s2.charAt(0);
char ch3 = s3.charAt(0);
String ros1 = s1.substring(1);
String ros2 = s2.substring(1);
String ros3 = s3.substring(1);
int ans = 0;
if (ch1 == ch2 && ch2 == ch3) {
ans = LCS3(ros1, ros2, ros3, strg) + 1;
} else {
int options[] = new int[6];
options[0] = LCS3(s1, ros2, ros3, strg);
options[1] = LCS3(ros1, s2, ros3, strg);
options[2] = LCS3(ros1, ros2, s3, strg);
options[3] = LCS3(s1, s2, ros3, strg);
options[4] = LCS3(s1, ros2, s3, strg);
options[5] = LCS3(ros1, s2, s3, strg);
ans = 0;
for (int val : options)
ans = Math.max(ans, val);
}
strg[s1.length()][s2.length()][s3.length()] = ans;
return ans;
}
------------------------------------------------------------------------------------------------
19. Array Desciption (CSES)
Intuition->
Think about the DP definition DP[i][x], it says number of valid Arrays A[1..i] such that ith element = x.
If A[i] = 0 then I can change to it to x and then I can obtain some valid arrays where the ith Element is X.
If A[i] is already equal to x then also some valid arrays exist where the ith element is x but if it's not possible to have x at the ith position then no valid array exist where the ith element = x
public static long ArrayDescription(int n, int m, int[] arr) {
int[][] dp = new int[n + 1][m + 2];
for (int i = 1; i <= n; i++) {
for (int x = 1; x <= m; x++) {
if (i == 1) { // 1 size array.
if (arr[i] == 0 || arr[i] == x) {
dp[i][x] = 1;
} else
dp[i][x] = 0;
} else {
if (arr[i] == 0 || arr[i] == x) {
dp[i][x] = ((dp[i - 1][x - 1] + dp[i - 1][x]) % MOD + dp[i - 1][x + 1]) % MOD;
} else {
dp[i][x] = 0;
}
}
}
}
long ans = 0;
for (int x = 1; x <= m; x++) {
ans = (ans + dp[n][x]) % MOD;
}
return ans;
}
-----------------------------------------------------------------------------------------------
Important Note: In questions like longest subsequence or substring , try to find out the ans which ends at current element.
------------------------------------------------------------------------------------------------
20. Longest Increasing Subsequence
Intuition-> at each index we are finding the LIS which ends with arr[idx]. at last we are finding the max in the dp array.
Iterative->
public int lengthOfLIS(int[] nums) {
int n=nums.length;
int[]dp=new int[n];
int omax=0;
for(int i=0;i<n;i++){
int max=0;
for(int j=0;j<i;j++){
if(nums[i]>nums[j]){
if(dp[j]>max){
max=dp[j];
}
}
}
dp[i]=1+max;
if(dp[i]>omax){
omax=dp[i];
}
}
return omax;
}
NlogN Approach->https://www.youtube.com/watch?v=nf3YG4CnTbg / Kartik Arora
->Here, we are observing that if there are two candidates which are helping to extend the subsequence with same values for eg (10) (4) 6 11 then we show smaller candidate as it will help in extending more length in future just in
(1) (1)
this case if we chose 10 then it get extended to 10 11 length (2), but if we chose element 4 then it get extended to 4 6 11 length (3), this also depicts that at a particular length there will be only 1 length corresponding to it.
And also that sorted values contain sorted advantages
That's the intuition behind this complexity.
public static int LISOptimised(int[] nums) {
int n = nums.length;
int dp[] = new int[n];
dp[0] = 1;
TreeMap<Integer, Integer> candidate = new TreeMap<Integer, Integer>();
candidate.put(nums[0], dp[0]);
for (int i = 1; i < n; i++) {
dp[i] = 1 + getBestCandidate(candidate, nums[i]);
insertCandidate(candidate, nums[i], dp[i]);
}
int max = 0;
for (int i = 0; i < dp.length; i++) {
max = Math.max(max, dp[i]);
}
return max;
}
private static int getBestCandidate(TreeMap<Integer, Integer> candidate, int val) {
if (candidate.lowerKey(val) == null) {
return 0;
}
return candidate.get(candidate.lowerKey(val));
}
public static void insertCandidate(TreeMap<Integer, Integer> candidate, int k, int v) {
if (candidate.getOrDefault(k, 0) >= v)
return;
candidate.put(k, v);
Integer key = candidate.higherKey(k);
while (key != null && candidate.get((int) key) <= v) { // means key giving
// less advantage
// but is more in //
// value
Integer temp = key;
key = candidate.higherKey((int) temp);
candidate.remove(temp);
}
}
-------------------------
Easiest Approach-> NlogN
public static int LISOptimised(int[] nums) {
int n = nums.length;
int dp[] = new int[n + 1];
dp[0] = Integer.MIN_VALUE;
for (int i = 1; i <= n; i++) {
dp[i] = Integer.MAX_VALUE;
}
for (int i = 0; i < n; i++) {
int idx = UpperBound(dp, 0, n, nums[i]);
if (idx >= dp.length)
continue;
//nums[i]>dp[idx-1] checked for strictly increasing seq.
] if (nums[i] > dp[idx - 1] && nums[i] < dp[idx]) { //though nums[i] always<dp[i]
dp[idx] = nums[i]; //because we found upper bound
}
}
int ans = 0;
for (int i = n; i > 0; i--) {
if (dp[i] != Integer.MAX_VALUE) {
ans = i;
break;
}
}
return ans;
}
public static int UpperBound(int[] arr, int lo, int hi, int val) {
int ans = 0;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (arr[mid] <= val) {
lo = mid + 1;
ans = mid;
} else {
hi = mid - 1;
}
}
return ans + 1;
}
------------------------------------------------------------------------------------------------
21. Unbounded Knapsack
public static int unboundedKnapsack(int[] wt, int[] price, int W) {
int[] dp = new int[W + 1];
for (int i = 0; i < wt.length; i++) {
for (int j = 1; j <=W; j++) {
if(j>=wt[i]) {
dp[j]=Math.max(dp[j], price[i]+dp[j-wt[i]]);
}
}
}
return dp[W];
}
public static int unboundedKnapsack(int[] wt, int[] price, int cap, int vidx, int[][] dp) {
if (cap < 0) {
return 0;
}
if (vidx == price.length)
return 0;
if (dp[vidx][cap] != -1)
return dp[vidx][cap];
int in = 0, ex = 0;
if (cap >= wt[vidx]) {
in = unboundedKnapsack(wt, price, cap - wt[vidx], vidx, dp) + price[vidx];
}
ex = unboundedKnapsack(wt, price, cap, vidx + 1, dp);
int ans = Math.max(in, ex);
dp[vidx][cap] = ans;
return ans;
}
------------------------------------------------------------------------------------------------
22. Longest Repeated Subsequence
Logic-> find lcs of string with itself keeping in mind that both equal characters have diff indx
Memoization->
public int LRS(String str, int i, int j, int[][] dp) {
if (i == 0 || j == 0) {
return 0;
}
if (dp[i][j] != -1)
return dp[i][j];
int ans = 0;
if (i != j && str.charAt(i - 1) == str.charAt(j - 1)) {
ans = 1 + LRS(str, i - 1, j - 1, dp);
} else {
int fp = LRS(str, i - 1, j, dp);
int sp = LRS(str, i, j - 1, dp);
ans = Math.max(fp, sp);
}
dp[i][j] = ans;
return ans;
}
Tabulation->
public int LRSBU(String str) {
int[][] dp = new int[str.length() + 1][str.length() + 1];
for (int row = str.length() - 1; row >= 0; row--) {
for (int col = str.length() - 1; col >= 0; col--) {
char ch1 = str.charAt(row);
char ch2 = str.charAt(col);
int ans = 0;
if (ch1 == ch2 && row != col) {
ans = dp[row + 1][col + 1] + 1;
} else {
int fp = dp[row][col + 1];
int sp = dp[row + 1][col];
ans = Math.max(fp, sp);
}
dp[row][col] = ans;
}
}
return dp[0][0];
}
------------------------------------------------------------------------------------------------
23. Longest Common Substring
Logic-> compare all prefixes of string 1 with prefixes of string 2 and find longest common suffix (which is ultimately longest common substring)
*some substring is always a suffix of some prefix , this is the intuition
->Dry run bottom up approach for better understanding.
int longestCommonSubstr(String s1, String s2, int n, int m){
int [][]dp=new int[n+1][m+1];
int max=0;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
char c1=s1.charAt(i-1);
char c2=s2.charAt(j-1);
if(c1!=c2){
dp[i][j]=0;
}else{
dp[i][j]=1+dp[i-1][j-1]; //common sufffix
}
if(dp[i][j]>max)
max=dp[i][j];
}
}
return max;
}
Memoization->
------------------------------------------------------------------------------------------------
24. Count Palindromic Substrings
logic-> We make a 2d array and there row represent the starting character and column represents the ending character. to check whether string is palidrome or not, we just have to check for 2 conditions.
i) starting and ending character should be same,
ii) internal string that is (i+1,j-1)string should be palidrome.
if there is n gap between characters then there is n+1 characters
public int countSubstrings(String s) {
boolean[][]dp= new boolean[s.length()][s.length()];
int count=0;
for(int gap=0;gap<s.length();gap++){
for(int i=0,j=gap;j<s.length();i++,j++){//Every slide starts from first row but ends
if(gap==0){ //with last column
dp[i][j]=true;
}else if(gap==1){
if(s.charAt(i)==s.charAt(j))
dp[i][j]=true;
}else{
if(s.charAt(i)==s.charAt(j) && dp[i+1][j-1])
dp[i][j]=true;
}
if(dp[i][j])
count++;
}
}
return count;
}
------------------------------------------------------------------------------------------------
25.a) Count Palidromic Subsequences
*) str= c1+m+c2
->sq(str)= c1(yes/no)+ sq(m) + c2(yes/no)
->sq(c1 m)=c1(yes/no) +sq(m)
->sq(m c2)=sq(m)+c2(yes/no)
->sq(m)=sq(m)
sq(c1m)->{_sq(m)}-->cn1, {c1sq(m)_}-->cn3
sq(mc2)->{sq(m)_}-->cn1, {sq(m)c2}-->cn2
count(c1+m+c2)-> cn1{_sq(m)_} , cn2{_sq(m)c2} , cn3{c1sq(m)_} , cn4{c1sq(m)c2}
if(c1==c2){
count=cn1+cn2+cn3+cn4
count=cn1+cn2+cn3+(cn1+1)
count=1+(cn1+cn2)+(cn1+cn3)
count=1+count(mc2)+count(c1m)
}else if(c1!=c2){
count=cn1+cn2+cn3+0
count=cn1+cn2+cn3
count=cn1+cn2+cn3+cn1-cn1
count=(cn1+cn2)+(cn1+cn3)-count(m){c1}
count=count(mc2)+count(c1m)-count(m)
}
public long CountPalidromicSubsequences(String str) {
long[][] dp = new long[str.length()][str.length()];
for (int gap = 0; gap < str.length(); gap++) {
for (int i = 0, j = gap; j < str.length(); i++, j++) {
if (gap == 0) {
dp[i][j] = 1;
} else if (gap == 1) {
dp[i][j] = (str.charAt(i) == str.charAt(j)) ? 3 : 2;
} else {
if (str.charAt(i) == str.charAt(j)) {
(prefix) (suffix)
dp[i][j] = ((dp[i][j - 1] + dp[i + 1][j]) % MOD + 1) % MOD;
} else {
dp[i][j] = ((dp[i][j - 1] + dp[i + 1][j]) % MOD - dp[i + 1][j - 1]+MOD) % MOD;
}
}
}
}
return dp[0][str.length() - 1];
}
25.b) Count distinct Palidromic subsequences ->https://www.youtube.com/watch?v=fvYlinirmFg
-> here we used set theory (inclusion - exclusion principle) ans also some explaination from above question
(1u2u3)=1+2+3-(1i2)-(2i3)-(1i3)+(1i2i3)
Using above explaination->
if(c1!=c2){
(distinct palidromic subsequence)
dps(c1mc2)=dps(c1m)+dps(mc2)-dps(m);
//get understanding through set theory s2,s3,s1 and through above formula find distinct palidromic non-empty subsequence (union)
i->intersection
=s1+s2+s3-(s1is2)-(s1is3)-(s2is3)+(s1is2is3)
since in set c1m and set mc2 there is nothing common so
=s1+s2+s3-(s1is2)-(s1is3)-0+0 +s1-s1
(s1+s2-(s1is2))+(s1+s3-(s1is3))-s1
which gives above formula
}else if( c1==c2){
if(mid string doesn't have c1)
=s1+s2+s3+s4-(s1is2)-(s1is3)-(s1is4)-(s2is3)-(s2is4)-(s3is4)+(s1is2is3)+(s2is3is4)+(s1is3is4)+(s1is2is4)-(s1is2is3is4)
dps(c1mc2)=2dps(m)+2 proved through set theory, it will cover all 4{(c1m),(m),(mc2),(c1mc2)} cases and then come to some conclusion
}else if( mid string have 1 c1){
dps(c1mc2)=2dps(m)+1
just make sets all 4 sets just like above and then after analyzing you will found that only s1(m)and s4(c1mc2) will be left as we know that s4 contains s1+1 subsequence (extra 1 because empty string become valid)
}else if( mid string have more than 1 c1){
dps(c1mc2)=2*dps(m)-dps(m')
}
###And in this question also we are representing row as starting character, and column as ending character
public int CountDifferentPalindromicSubsequences(String str){
int dp[][]=new int[str.length()][str.length()];
int[]prev=new int[str.length()]; //this will give me indx of prev (same)character if any
HashMap<Character,Integer>map=new HashMap<>();
for(int i=0;i<prev.length;i++){
if(!map.containsKey(str.charAt(i))){
prev[i]=-1;
}else{
prev[i]=map.get(str.charAt(i));
}
map.put(str.charAt(i),i);
}
map.clear();
int[]next=new int[str.length()];
for(int i=next.length-1;i>=0;i--){
if(!map.containsKey(str.charAt(i))){
next[i]=-1;
}else{
next[i]=map.get(str.charAt(i));
}
map.put(str.charAt(i),i);
}
for(int gap=0;gap<str.length();gap++){
for(int i=0,j=gap;j<str.length();i++,j++){
if(gap==0){
dp[i][j]=1;
}else if(gap==1){ //2 characters
dp[i][j]=2;
}else{
if(str.charAt(i)!=str.charAt(j)){
dp[i][j]=((dp[i+1][j]+dp[i][j-1])%m-dp[i+1][j-1])%m;
}else{
int n=next[i];
int p=prev[j];
if(n>p){ //0 same character in mid
dp[i][j]=(2*dp[i+1][j-1]%m+2)%m;
}else if(n==p){ //1 same character
dp[i][j]=(2*dp[i+1][j-1]%m+1)%m;
}else{ // more than 1 same character
dp[i][j]=(2*dp[i+1][j-1]%m-dp[n+1][p-1])%m;
}
}
}
if (dp[i][j] < 0) dp[i][j] = (dp[i][j] + m )%m;
}
}
return dp[0][str.length()-1];
}
------------------------------------------------------------------------------------------------
26. Longest Palindromic Subsequence
-> Method1) Find LCS of (str,reverse of str).
Method 2)->
*) str= c1+m+c2
->sq(str)= c1(yes/no)+ sq(m) + c2(yes/no)
->sq(c1 m)=c1(yes/no) +sq(m)
->sq(m c2)=sq(m)+c2(yes/no)
->sq(m)=sq(m)
s1->m , s2-> c1m , s3-> mc2 , s4-> c1mc2
now if(c1!=c2){ //ans can't lie in set4
-> max(lps(s1),lps(s2),lps(s3))
but lps(s2) represents ->(s1,s2), and similarly lps(s3) represents (s1,s3)
so ans=Max(lps(s2),lps(s3))
}else{ //ans only lies in set 4
lps=lps(mid)+2
}
public int longestPalindromeSubseq(String s) {
int[][]dp=new int[s.length()][s.length()];
for(int gap=0;gap<s.length();gap++){
for(int i=0,j=gap;j<s.length();i++,j++){
char c1=s.charAt(i);
char c2=s.charAt(j);