Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Graph Algorithms and popular Dynamic Programming questions. #8

Open
wants to merge 75 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
75 commits
Select commit Hold shift + click to select a range
b8e01df
Create Graphs
SharatMehrotra May 14, 2021
363066e
Delete Graphs
SharatMehrotra May 14, 2021
f644379
Create Graphs
SharatMehrotra May 14, 2021
3b81b37
Delete Graphs
SharatMehrotra May 14, 2021
6caa4e9
Create Dijkstra.cpp
SharatMehrotra May 14, 2021
b531080
Create BellmanFord.cpp
SharatMehrotra May 14, 2021
3118e6f
Create FloydWarshall.cpp
SharatMehrotra May 14, 2021
e75daef
Update BellmanFord.cpp
SharatMehrotra May 14, 2021
30f19fd
Create Prims.cpp
SharatMehrotra May 14, 2021
a2b4aee
Create Dfs.cpp
SharatMehrotra May 14, 2021
0cd7c64
Rename Dfs.cpp to DFS.cpp
SharatMehrotra May 14, 2021
9b35691
Create BFS.cpp
SharatMehrotra May 14, 2021
cd4768e
Create CycleDetection_DirectedGraph.cpp
SharatMehrotra May 14, 2021
10cb158
Create CycleDetection_UndirectedGraph.cpp
SharatMehrotra May 14, 2021
b8a72e4
Create TopologicalSort.cpp
SharatMehrotra May 14, 2021
5e6cf97
Create README.md
SharatMehrotra May 14, 2021
6f3b8a2
Create LongestPathBtwAnyPairOfVert.cpp
SharatMehrotra May 14, 2021
8204baf
Create MotherVertex.cpp
SharatMehrotra May 15, 2021
a019d84
Create BipartiteGraph.cpp
SharatMehrotra May 15, 2021
352a006
Update BipartiteGraph.cpp
SharatMehrotra May 15, 2021
2844d9d
Create DisjointSetUnion.cpp
SharatMehrotra May 15, 2021
ee8c785
Update DisjointSetUnion.cpp
SharatMehrotra May 15, 2021
bfd1fa4
Create Bridges.cpp
SharatMehrotra May 15, 2021
9d14fd6
Create CutVertices.cpp
SharatMehrotra May 15, 2021
23cd7fa
Update README.md
SharatMehrotra May 15, 2021
0e12c35
Update LongestPathBtwAnyPairOfVert.cpp
SharatMehrotra May 16, 2021
1383245
Create LongestCommonSubsequence.cpp
SharatMehrotra May 18, 2021
5d32472
Create LongestPalindromicSubsequence.cpp
SharatMehrotra May 19, 2021
0728d40
Create EditDistance.cpp
SharatMehrotra May 19, 2021
0ff1283
Create RepeatingSubsequence.cpp
SharatMehrotra May 19, 2021
2f63c62
Create DistinctSubsequences.cpp
SharatMehrotra May 19, 2021
88908e7
Create InterleavingStrings.cpp
SharatMehrotra May 19, 2021
4eb03c5
Create RegularExpressions.cpp
SharatMehrotra May 19, 2021
0fec375
Create ScrambleString.cpp
SharatMehrotra May 19, 2021
278056d
Create FlipArray.cpp
SharatMehrotra May 19, 2021
06ee3ac
Create 01Knapsack.cpp
SharatMehrotra May 19, 2021
f64d6cc
Create TusharsBirthday.cpp
SharatMehrotra May 19, 2021
ed01556
Create MaxSumPathInTree.cpp
SharatMehrotra May 19, 2021
c946ccf
Create WordBreak.cpp
SharatMehrotra May 19, 2021
8e697af
Create PalindromePartition.cpp
SharatMehrotra May 19, 2021
857ee1b
Create UniqueBinarySearchTrees.cpp
SharatMehrotra May 19, 2021
24df61b
Create TilingWithDominos.cpp
SharatMehrotra May 19, 2021
c5ff1aa
Create SubsetSum.cpp
SharatMehrotra May 19, 2021
5dfe84f
Create PaintHouse.cpp
SharatMehrotra May 19, 2021
45c9280
Create MinSubsetDifference.cpp
SharatMehrotra May 19, 2021
68b26c7
Create UniquePathsInGrid.cpp
SharatMehrotra May 19, 2021
00ee499
Create MaximumSizeSquareSub-matrix.cpp
SharatMehrotra May 19, 2021
b9d68fd
Create LengthOfLongestBitonicSubsequence.cpp
SharatMehrotra May 19, 2021
4e46a8b
Create SmallestSequenceWithPrimes.cpp
SharatMehrotra May 19, 2021
57bbbf9
Create WaysToDecode.cpp
SharatMehrotra May 19, 2021
e44963d
Create LongestIncreasingSubsequence.cpp
SharatMehrotra May 19, 2021
42ad8c7
Create IntersectingChordsInCircles.cpp
SharatMehrotra May 19, 2021
24f9d01
Create JumpGameArray.cpp
SharatMehrotra May 19, 2021
e527c4c
Create MinJumpsArray.cpp
SharatMehrotra May 19, 2021
0c3730d
Create LongestArithmeticProgression.cpp
SharatMehrotra May 19, 2021
e40bcc2
Create BestTimeToBuy&SellStockAtmostBTimes.cpp
SharatMehrotra May 19, 2021
b18139b
Create CoinsInALine.cpp
SharatMehrotra May 19, 2021
9fa867e
Create LongestValidParentheses.cpp
SharatMehrotra May 19, 2021
7b5943b
Create KingdomWar.cpp
SharatMehrotra May 19, 2021
3f32a2d
Create MaximumPathInTriangle.cpp
SharatMehrotra May 19, 2021
10c0a2b
Create DungeonPrincess.cpp
SharatMehrotra May 19, 2021
c50320f
Create MinSumPath.cpp
SharatMehrotra May 19, 2021
f9862b2
Create MinPathInTriangle.cpp
SharatMehrotra May 19, 2021
7f512e9
Create MaxRectangleInBinaryMatrix.cpp
SharatMehrotra May 19, 2021
140100b
Create SubMatrixWithSumZero.cpp
SharatMehrotra May 19, 2021
4a061e9
Create CoinSumInfinite.cpp
SharatMehrotra May 19, 2021
ba27992
Create MaxProductSubarray.cpp
SharatMehrotra May 19, 2021
a5feb19
Create ChainOfPairs.cpp
SharatMehrotra May 19, 2021
7b311d0
Create Arrange.cpp
SharatMehrotra May 19, 2021
abee8da
Create MaxSumWithoutAdjacent.cpp
SharatMehrotra May 19, 2021
813ba34
Create IncreasingPathInMatrix.cpp
SharatMehrotra May 19, 2021
a36f1bd
Create MergeElements.cpp
SharatMehrotra May 19, 2021
ac1cbf4
Update IncreasingPathInMatrix.cpp
SharatMehrotra May 19, 2021
e2b7b85
Update BellmanFord.cpp
SharatMehrotra Jun 10, 2021
4a17786
Update BellmanFord.cpp
SharatMehrotra Jun 10, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions DynamicProgramming/01Knapsack.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
Given two integer arrays A and B of size N each which represent values and weights associated with N items respectively.

Also given an integer C which represents knapsack capacity.

Find out the maximum value subset of A such that sum of the weights of this subset is smaller than or equal to C.

NOTE:
You cannot break an item, either pick the complete item, or don’t pick it (0-1 property).
*/
int Solution::solve(vector<int> &A, vector<int> &B, int C) {
int n=A.size();
int m=B.size();
vector<vector<int>>dp(n+1,vector<int>(C+1,0));
for(int i=1;i<=n;i++)dp[i][0]=0;
for(int i=1;i<=C;i++) dp[0][i]=0;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=C;j++)
{
dp[i][j]=dp[i-1][j];
if(j>=B[i-1])
{
dp[i][j]=max(dp[i][j], A[i-1] +dp[i-1][j-B[i-1]]);
}
}
}
return dp[n][C];
}
35 changes: 35 additions & 0 deletions DynamicProgramming/Arrange.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*You are given a sequence of black and white horses, and a set of K stables numbered 1 to K. You have to accommodate the horses into the stables in such a way that the following conditions are satisfied:

You fill the horses into the stables preserving the relative order of horses. For instance, you cannot put horse 1 into stable 2 and horse 2 into stable 1. You have to preserve the ordering of the horses.
No stable should be empty and no horse should be left unaccommodated.
Take the product (number of white horses * number of black horses) for each stable and take the sum of all these products. This value should be the minimum among all possible accommodation arrangements*/

int solve(int i,int k,int n,string A, vector<vector<int>>&t)
{
if(i>=n && k>0) return INT_MAX/2;
if(t[i][k]!=-1) return t[i][k];
int w=0,b=0;
if(k==1)
{
for(int j=i;j<n;j++)
{
if(A[j]=='W') w++;
else b++;
}
return t[i][k]= b*w;
}
int ans=INT_MAX/2;
for(int j=i;j<n;j++)
{
if(A[j]=='W') w++;
else b++;
int temp=w*b+ solve(j+1,k-1,n,A,t);
ans=min(temp,ans);
}
return t[i][k]=ans;
}
int Solution::arrange(string A, int B) {
if(B>A.size()) return -1;
vector<vector<int>>t(A.size()+1,vector<int>(B+1,-1));
return solve(0,B,A.size(),A,t);
}
22 changes: 22 additions & 0 deletions DynamicProgramming/BestTimeToBuy&SellStockAtmostBTimes.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/*Given an array of integers A of size N in which ith element is the price of the stock on day i.

You can complete atmost B transactions.

Find the maximum profit you can achieve.

NOTE: You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).*/
int Solution::solve(vector<int> &A, int B) {
int n=A.size();
B=min(B,n/2);
vector<vector<int>>dp(n,vector<int>(B+1,0));
for(int j=1;j<=B;j++)
{
int prev=INT_MIN;
for(int i=1;i<n;i++)
{
prev=max(prev,dp[i-1][j-1]-A[i-1]);
dp[i][j]=max(dp[i-1][j],prev+A[i]);
}
}
return dp[n-1][B];
}
26 changes: 26 additions & 0 deletions DynamicProgramming/ChainOfPairs.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*Given a N * 2 array A where (A[i][0], A[i][1]) represents the ith pair.

In every pair, the first number is always smaller than the second number.

A pair (c, d) can follow another pair (a, b) if b < c , similarly in this way a chain of pairs can be formed.

Find the length of the longest chain subsequence which can be formed from a given set of pairs.*/


int Solution::solve(vector<vector<int> > &A) {
int n=A.size();
vector<int>dp(n,1);
int ans=1;
for(int i=0;i<n;i++)
{
for(int j=0;j<i;j++)
{
if(A[i][0]>A[j][1])
{
dp[i]=max(dp[i],dp[j]+1);
}
ans=max(ans,dp[i]);
}
}
return ans;
}
18 changes: 18 additions & 0 deletions DynamicProgramming/CoinSumInfinite.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/*You are given a set of coins S. In how many ways can you make sum N assuming you have infinite amount of each coin in the set.

Note : Coins in set S will be unique. Expected space complexity of this problem is O(N).*/

int Solution::coinchange2(vector<int> &A, int B) {
int n=A.size();
vector<long long int>dp(B+1,0);
dp[0]=1;
sort(A.begin(),A.end());
for(int i=0;i<n;i++)
{
for(int j=A[i];j<=B;j++)
{
dp[j]=(dp[j]% 1000007+dp[j-A[i]]% 1000007)% 1000007;
}
}
return dp[B]% 1000007;
}
23 changes: 23 additions & 0 deletions DynamicProgramming/CoinsInALine.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*There are A coins (Assume A is even) in a line.

Two players take turns to take a coin from one of the ends of the line until there are no more coins left.

The player with the larger amount of money wins, Assume that you go first.

Return the maximum amount of money you can win.*/
int ans(int start,int end,vector<int>&A,vector<vector<int>>&dp)
{
if(start==end) return dp[start][end]=A[end];
if(dp[start][end]!=-1) return dp[start][end];
int res=max(A[start]-ans(start+1,end,A,dp), A[end]-ans(start,end-1,A,dp));
return dp[start][end]=res;
}
int Solution::maxcoin(vector<int> &A) {
int n=A.size();
vector<vector<int>>dp(n,vector<int>(n,-1));
ans(0,A.size()-1,A,dp);
int sum=0;
for(int i=0;i<A.size();i++) sum+=A[i];

return (dp[0][n-1]+sum)/2;
}
32 changes: 32 additions & 0 deletions DynamicProgramming/DistinctSubsequences.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
Given two sequences A, B, count number of unique ways in sequence A, to form a subsequence that is identical to the sequence B.
*/

int Solution::numDistinct(string A, string B) {
int n=A.size();
int m=B.size();
vector<vector<int>>dp(n+1,vector<int>(m+1,0));
for(int i=0;i<=n;i++)
{
dp[i][0]=1;
}
for(int i=1;i<=m;i++)
{
dp[0][i]=0;
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
if(A[i-1]==B[j-1])
{
dp[i][j]=dp[i-1][j]+dp[i-1][j-1];
}
else
{
dp[i][j]=dp[i-1][j];
}
}
}
return dp[n][m];
}
22 changes: 22 additions & 0 deletions DynamicProgramming/DungeonPrincess.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/*The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess.

The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately.

Some of the rooms are guarded by demons, so the knight loses health (negative integers) upon entering these rooms; other rooms are either empty (0’s) or contain magic orbs that increase the knight’s health (positive integers).

In order to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.
*/
int Solution::calculateMinimumHP(vector<vector<int> > &A) {
int r=A.size(),c=A[0].size();
for(int i=r-1;i>=0;i--)
{
for(int j=c-1;j>=0;j--)
{
if(i==r-1&&j==c-1) A[i][j]=max(1-A[i][j],1);
else if(j==c-1) A[i][j]=max(A[i+1][j]-A[i][j],1);
else if(i==r-1) A[i][j]=max(A[i][j+1]-A[i][j],1);
else A[i][j]=max(min(A[i+1][j],A[i][j+1])-A[i][j],1);
}
}
return A[0][0];
}
34 changes: 34 additions & 0 deletions DynamicProgramming/EditDistance.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
Given two strings A and B, find the minimum number of steps required to convert A to B. (each operation is counted as 1 step.)

You have the following 3 operations permitted on a word:

Insert a character
Delete a character
Replace a character
*/
int Solution::minDistance(string A, string B) {
int n=A.size();
int m=B.size();
vector<vector<int>>dp(n+1,vector<int>(m+1,INT_MAX));
for(int i=0;i<=n;i++)
{
for(int j=0;j<=m;j++)
{
if(i==0 || j==0)
{
if(i==0) dp[i][j]=j; // need to delete all char of one string to make it equal to 0
else dp[i][j]=i; // need to insert...
}
else if(A[i-1]==B[j-1])
{
dp[i][j]=dp[i-1][j-1]; // same char. no need of operation
}
else
{
dp[i][j]=1+min(dp[i-1][j],min(dp[i][j-1],dp[i-1][j-1]));
}
}
}
return dp[n][m];
}
37 changes: 37 additions & 0 deletions DynamicProgramming/FlipArray.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
Given an array of positive elements, you have to flip the sign of some of its elements such that the resultant sum of the elements of array should be minimum non-negative(as close to zero as possible). Return the minimum no. of elements whose sign needs to be flipped such that the resultant sum is minimum non-negative.
*/
int Solution::solve(const vector<int> &A) {
int n = A.size();
int sumv = 0;
for(int i=0;i<n;i++){
sumv += A[i];
}
int req = sumv/2;
vector<vector<int> > dp(n+1,vector<int>(req+1,INT_MAX));
dp[0][0] = 0;
for(int i=0;i<=n;i++)
{
dp[i][0] = 0;
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=req;j++)
{
int a=INT_MAX;
int b;
if(j>=A[i-1])
{
a = dp[i-1][j-A[i-1]];
if(a!=INT_MAX) a+=1;
}
b = dp[i-1][j];
dp[i][j] = min(a,b);
}
}
for(int i=req;i>=0;i--){
if(dp[n][i]!=INT_MAX){
return dp[n][i];
}
}
}
47 changes: 47 additions & 0 deletions DynamicProgramming/IncreasingPathInMatrix.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*Given a 2D integer matrix A of size N x M.

From A[i][j] you can move to A[i+1][j], if A[i+1][j] > A[i][j], or can move to A[i][j+1] if A[i][j+1] > A[i][j].

The task is to find and output the longest path length if we start from (0, 0).

NOTE:

If there doesn't exist a path return -1.*/
int Solution::solve(vector<vector<int> > &A) {
int n=A.size();
int m=A[0].size();
vector<vector<int>>dp(n,vector<int>(m,0));
int ans=-1;
dp[0][0]=1;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(i==0 && j==0) continue;
if(i==0 || j==0)
{
if(i==0)
{
if(A[i][j]>A[i][j-1] && dp[i][j-1]!=0)
dp[i][j]=1+dp[i][j-1];
}
else
{
if(A[i][j]>A[i-1][j] && dp[i-1][j]!=0)
dp[i][j]=1+dp[i-1][j];
}
}
else
{
if(A[i][j]>A[i-1][j] && dp[i-1][j]!=0)
dp[i][j]=max(dp[i][j],1+dp[i-1][j]);
if(A[i][j]>A[i][j-1] && dp[i][j-1]!=0)
{
dp[i][j]=max(dp[i][j],1+dp[i][j-1]);
}
}
}
}
if(dp[n-1][m-1]==0) return -1;
return dp[n-1][m-1];
}
42 changes: 42 additions & 0 deletions DynamicProgramming/InterleavingStrings.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
//Given A, B, C, find whether C is formed by the interleaving of A and B.

int Solution::isInterleave(string A, string B, string C) {
int n=A.size();
int m=B.size();
vector<vector<bool>>dp(n+1,vector<bool>(m+1,false));
for(int i=0;i<=n;i++)
{
for(int j=0;j<=m;j++)
{
if(i==0 && j==0)
{
dp[i][j]=true;
}
else if(i==0)
{
if(B[j-1]==C[i+j-1])
dp[i][j]=dp[i][j-1];
}
else if(j==0)
{
if(A[i-1]==C[i+j-1])
{
dp[i][j]=dp[i-1][j];
}
}
else if(A[i-1]==C[i+j-1] && B[j-1]!=C[i+j-1])
{
dp[i][j]=dp[i-1][j];
}
else if(B[j-1]==C[i+j-1] && A[i-1]!=C[i+j-1])
{
dp[i][j]=dp[i][j-1];
}
else if(C[i+j-1]==B[j-1] && C[i+j-1]==A[i-1])
{
dp[i][j]=dp[i-1][j] || dp[i][j-1];
}
}
}
return dp[n][m];
}
17 changes: 17 additions & 0 deletions DynamicProgramming/IntersectingChordsInCircles.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
int Solution::chordCnt(int A)
{
long long int m = 1000000007;
long long int dp[A+1];
dp[0] = 1;
dp[1]=1;
for(long long int i=2;i<=A;i++)
{
dp[i] = 0;
for(long long int j=0;j<i;j++)
{
long long int temp = (dp[j]%m * dp[i-j-1]%m)%m;
dp[i] = (dp[i]%m+temp%m)%m;
}
}
return (dp[A]+m)%m;
}
Loading