-
Notifications
You must be signed in to change notification settings - Fork 1
/
Dynamic Programming.txt
2929 lines (2515 loc) · 91.2 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
Important Concetps
-> All DP problems according to its type -> https://leetcode.com/discuss/study-guide/1000929/Solved-all-dynamic-programming-(dp)-problems-in-7-months
1) Whenever there will be relation like dp[i-1], dp[i-2] there can always be space optimization like
curr = accoding to question
prev2=prev;
prev=curr;
-> If there is a prev row & prev column, we can space optimise it.
-> in place of dp[i-1][j] we can write prev[j] and in place of dp[i][j-1] we can write curr[j-1].
& if there is array concept in space optimization then make it front array and next array and after work just set front array = next array
2) If there is any problem related to subsets for eg)
-> Count partitions with given difference s1-s2=d => total =s1+s2 => s2 = (total-d)/2;
-> Count subsets with sum k
-> Partition Equal subset sum => make total sum then find subset having sum total/2
-> Partition A set into two subsets with minimum Abs sum differece -> Q13) in Backtracking file
=> These all problems boils down to same. just by modifying the target.
3) In Partition type Dp
-> we see that we get different answers on different pattern pattern (like by different way, we get diff ans).
-> Here we take whole block of array and solve for every possible partition and calculate ans accordingly.
Rules:
-> In top down suppose we call for solve(1,n-1)<=>solve(i,j)
-> In bottom up since we write just opposite. but here is something to think about.
-> IN CASE OF PARTITION DP
-> for(int i=n-1;i>=1;i++) and for the jth loop it doesn't start 0 instead i or i+1
-> for(int j=i+1;j<n;j++) because i can't be greater than j to get valid set of blocks of array.
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];
}
-> Extreme Space Optimised with just 1D array (Striver's solution)
// here below we can't move w from 0 to capacity because if we do so then the prev values of dp array will be
override and as we know that for each w we are dependent on prev values of dp to compute the current ans.
public int solve(int[] weights, int[] values, int capacity) {
int n = values.length;
int[]dp = new int[capacity+1];
for(int idx = 0; idx<n; idx++){
for(int w = capacity; w>=0; w--){
int notTake = dp[w];
int take = Integer.MIN_VALUE;
if(w>=weights[idx]){
take = values[idx] + dp[w-weights[idx]];
}
dp[w]=Math.max(take,notTake);
}
}
return dp[capacity];
}
----------------- -------------------------------------------------------------------------------
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;
}
#) Minimum Insertions/Deletions to Convert String A to String B
-> Keep the equal portion intact.
Eg) abcd , anc
abcd -> 2 deletions + ac -> 1 insertions makes anc
-> Deletions = len(a)-lcs(a,b);
-> Insertions = len(b)-lcs(a,b);
-> ans = (len(a)+len(b) - 2 * LCS(A,B));
------------------------------------------------------------------------------------------------
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];
}
#) Printing LCS
-> after tabulation,get the 2d dp array.
int len = dp[n][m];
String ans = "";
for(int i=0;i<len;i++){
ans+="$";
}
O(m+n)
int idx = len-1;
int i=n, j=m;
while(i>0 && j>0){
if(s[i-1]==t[j-1]){
ans[idx]=s[i-1];
idx--;
i--,j--;
}else if(dp[i-1][j]>dp[i][j-1]{
i--;
}else{
j--;
}
}
System.out.println(ans);
------------------------------------------------------------------------------------------------
6. Palindromic Partitions/cuts
-> Time Complexity (N^3) -> (N^2)
->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)
// we are cutting prefixes here (Front partition)
-> We can create another dp table in which dp[I][j] will tell whether substring s(I,j) is palindrome or not hence check function's time complexity reduces to O(1) and overall time complexity to O(n^2)
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) -> Leetcode:377 (Combination Sum IV)
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=1;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;
}
Striver's way ->
public boolean canPartition(int[] nums) {
int sum=0;
for(int num:nums){
sum+=num;
}
if(sum%2!=0)return false;
int n = nums.length;
int[][]dp = new int[n+1][sum/2 +1];
for(int[]dpp:dp){
Arrays.fill(dpp,-1);
}
int tar = sum/2;
return partitionEqualSubsetSum(n-1,tar,nums,dp);
}
public boolean partitionEqualSubsetSum(int idx, int tar,int[]nums,int[][]dp){
if(tar==0)return true;
if(idx==0)return (nums[0]==tar);
if(dp[idx][tar]!=-1){
return (dp[idx][tar]==1)?true:false;
}
boolean pick = false;
if(tar>=nums[idx]){
pick = partitionEqualSubsetSum(idx-1,tar-nums[idx],nums,dp);
}
boolean notPick = partitionEqualSubsetSum(idx-1,tar,nums,dp);
boolean ans = pick || notPick;
dp[idx][tar] = ((ans)? 1:2);
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;
//if i wants to be single then dp[i-1] will be called to find out in how many ways i-1 can be single or paired up
// if i wants to pair up then it can be paired up with i-1 leaving itself, now if it get paired up then
//remaining members will be i-2 they can be single or paired up (through dp[i-2]) <- it will give ans for those, since this call will be
//called i-1 times therefore we multiplied this.
}
return dp[n];
}
------------------------------------------------------------------------------------------------
14. Binomial Coefficient Problem (nCr)
Formula Used-> C(n, r) = C(n-1, r) + C(n-1, r-1)
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, r) = P(n-1, r) + r*P(n-1, r-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[]hash=new int[n]; // it will store the prev index of LIS
Arrays.fill(dp,1);
int omax=0;
int lastmaxind = 0;
for(int i=0;i<n;i++){
int max=0;
hash[i]=i;
for(int j=0;j<i;j++){
if(nums[i]>nums[j]){
if(dp[j]>max){
max=dp[j];
hash[i]=j;
}
}
}
dp[i]=1+max;
if(dp[i]>omax){
omax=dp[i];
lastmaxind=i;
}
}
// in order to print the LIS
ArrayList<Integer>lis = new ArrayList<>();
lis.add(nums[lastmaxind]);
while(hash[lastmaxind]!=lastmaxind){
lastmaxind = hash[lastmaxind];
lis.add(nums[lastmaxind]);
}
Collections.reverse(lis);
return omax;
}
-> Print no of LIS
public int findNumberOfLIS(int[] nums) {
int n = nums.length;
int[]dp = new int[n];
int[]cnt = new int[n];
Arrays.fill(dp,1);
Arrays.fill(cnt,1);
int max = 0;
for(int i=0;i<n;i++){
for(int j=0;j<i;j++){
if(nums[i]>nums[j]){
if(dp[i]<dp[j]+1){
dp[i]=dp[j]+1;
cnt[i]=cnt[j];
}else if(dp[i]==dp[j]+1){
cnt[i]+=cnt[j];
}
}
}
max = Math.max(dp[i],max);
}
int count=0;
for(int i=0;i<n;i++){
if(dp[i]==max){
count+=cnt[i];
}
}
return count;
}
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 int lengthOfLIS(int[] nums) {
int n = nums.length;
int[]lis = new int[n+1];
Arrays.fill(lis,Integer.MAX_VALUE);
lis[0] = Integer.MIN_VALUE;
int ans=0;
for(int i=0;i<n;i++){
int val = nums[i];
int idx = lowerBound(lis,nums[i]);
ans = Math.max(idx,ans);
if(lis[idx]>=val){
lis[idx]=val;
}
}
return ans;
}
public int lowerBound(int[]dp, int val){
int l=0, h=dp.length-1;
int res = 0;
while(l<=h){
int mid = (l+h)>>1;
if(dp[mid]<val){
res=mid;
l=mid+1;
}else{
h=mid-1;
}
}
return res+1;
}
-> Striver's Approach
public int lengthOfLIS(int[] nums) {
ArrayList<Integer> temp = new ArrayList<>();
temp.add(nums[0]);
int len = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] > temp.get(temp.size() - 1)) {
len++;
temp.add(nums[i]);
} else {
int[] arr = temp.stream().mapToInt(id -> id).toArray();
int idx = LowerBound(arr, 0, temp.size(), nums[i]);
temp.set(idx, nums[i]);
}
}
return len; // or temp.size();
}
------------------------------------------------------------------------------------------------
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 / Maximum Length of Repeated Subarray (LeetCode 718)
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
pqabcxy <-compare all prefixes of both and find longest common suffix-> xyzabcp
# At point when we compare pqabc with xyzabc thats where we get our longest common suffix hence longest common substring.
-> abc here is suffix of these above prefixes in both <- 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;