-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay-25.txt
148 lines (107 loc) · 2.95 KB
/
Day-25.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
Dynamic Programming Part-I
1. Max Product Subarray
ANS. 1st approach ():
int maxProduct(vector<int>& nums) {
int n=nums.size();
int res=nums[0],maxi=nums[0],mini=nums[0];
for (int i=1;i<n;i++)
{
if (nums[i]<0)
{
swap(maxi,mini);
}
maxi=max(nums[i],nums[i]*maxi);
mini=min(nums[i],nums[i]*mini);
res=max(res,maxi);
}
return res;
}
2nd approach ():
2. Longest Increasing Subsequence
ANS. 1st approach ():
3. Longest Common Subsequence
ANS. 1st approach ():
int longestCommonSubsequence(string text1, string text2) {
int n=text1.size();
int m=text2.size();
vector<vector<int>> t(n+1,vector<int> (m+1,-1));
for (int i=0;i<n+1;i++)
t[i][0]=0;
for (int i=0;i<m+1;i++)
t[0][i]=0;
for (int i=1;i<n+1;i++)
{
for (int j=1;j<m+1;j++)
{
if (text1[i-1]==text2[j-1])
t[i][j]=1+t[i-1][j-1];
else
t[i][j]=max(t[i-1][j],t[i][j-1]);
}
}
return t[n][m];
s="";
int i=n,j=m;
while (i>0 && j>0)
{
if (text1[i-1]==text2[j-1])
{
s.push_back(text1[i-1]);
i--;
j--;
}
else if (t[i][j-1]>t[i-1][j])
j--;
else
i--;
}
reverse(s.begin(), s.end());
return s;
}
4. 0-1 Knapsack
ANS. 1st approach ():
int knapSack(int W, int wt[], int val[], int n)
{
int t[n+1][W+1];
for (int i=0;i<n+1;i++)
t[i][0]=0;
for (int i=0;i<W+1;i++)
t[0][i]=0;
for (int i=1;i<n+1;i++)
{
for (int j=1;j<W+1;j++)
{
if (wt[i-1]<=j)
t[i][j]=max(val[i-1]+t[i-1][j-wt[i-1]],t[i-1][j]);
else
t[i][j]=t[i-1][j];
}
}
return t[n][W];
}
5. Ones and Zeroes
ANS. 1st approach ():
6. Edit Distance
ANS. 1st approach ():
7. Maximum Sum increasing Subsequence
ANS. 1st approach ():
8. Matrix Chain Multiplication
ANS. 1st approach ():
int MCM(int arr[],int lb,int ub, vector<vector<int>> &t)
{
if (lb==ub) return 0;
if (t[lb][ub]!=-1)
return t[lb][ub];
int mini=INT_MAX;
for (int k=lb;k<=ub-1;k++)
{
int tempans=MCM(arr,lb,k,t)+MCM(arr,k+1,ub,t)+arr[lb-1]*arr[k]*arr[ub];
mini=min(mini,tempans);
}
return t[lb][ub]=mini;
}
int matrixMultiplication(int N, int arr[])
{
vector<vector<int>> t(N,vector<int> (N,-1));
return MCM(arr,1,N-1,t);
}