filename
stringlengths
7
140
content
stringlengths
0
76.7M
code/dynamic_programming/src/longest_common_subsequence/longest_common_subsequence.go
/* Part of Cosmos by OpenGenus Foundation */ package main import "fmt" /* Expect Output The length of LCS of ABCDEFGHIJKLMNOPQRABCEDG adn DEFNMJABCDEG is 9 */ func max(n1, n2 int) int { if n1 > n2 { return n1 } return n2 } func LCS(str1, str2 string) int { len1 := len(str1) len2 := len(str2) dp := make([][]int, len1+1) for v := range dp { dp[v] = make([]int, len2+1) } for i := 1; i <= len1; i++ { for j := 1; j <= len2; j++ { if str1[i-1] == str2[j-1] { dp[i][j] = dp[i-1][j-1] + 1 } else { dp[i][j] = max(dp[i][j-1], dp[i-1][j]) } } } return dp[len1][len2] } func main() { str1 := "ABCDEFGHIJKLMNOPQRABCEDG" str2 := "DEFNMJABCDEG" lcs := LCS(str1, str2) fmt.Printf("The length of LCS of %s adn %s is %d\n", str1, str2, lcs) }
code/dynamic_programming/src/longest_common_subsequence/longest_common_subsequence.java
// Part of Cosmos by OpenGenus Foundation class LongestCommonSubsequence { /* Returns length of LCS for X[0..m-1], Y[0..n-1] */ int lcs( char[] X, char[] Y, int m, int n ) { int L[][] = new int[m+1][n+1]; //L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] for (int i=0; i<=m; i++) { for (int j=0; j<=n; j++) { if (i == 0 || j == 0) { L[i][j] = 0; } else if (X[i-1] == Y[j-1]) { // if there is a match L[i][j] = L[i-1][j-1] + 1; // increate lcs value by 1 } else { // else L[i][j] = Math.max(L[i-1][j], L[i][j-1]); // choose max value till now } } } return L[m][n]; } public static void main(String[] args) { LongestCommonSubsequence lcs = new LongestCommonSubsequence(); String s1 = "AGGAGTCTAGCTAB"; String s2 = "AGXGTTXAYBATCGAT"; char[] X=s1.toCharArray(); char[] Y=s2.toCharArray(); int m = X.length; int n = Y.length; System.out.println("Length of LCS is" + " " + lcs.lcs( X, Y, m, n ) ); } }
code/dynamic_programming/src/longest_common_subsequence/longest_common_subsequence.php
<?php function longestCommonSubsequence($x , $y) { $x_len = strlen($x); $y_len = strlen($y) ; for ($i = 0; $i <= $x_len; $i++) { for ($j = 0; $j <= $y_len; $j++) { if ($i == 0 || $j == 0) $dp[$i][$j] = 0; else if ($x[$i - 1] == $y[$j - 1]) $dp[$i][$j] = $dp[$i - 1][$j - 1] + 1; else $dp[$i][$j] = max($dp[$i - 1][$j], $dp[$i][$j - 1]); } } return $dp[$x_len][$y_len]; } $a = "AGGTAB"; $b = "GXTXAYB"; echo "Length of LCS : ", longestCommonSubsequence($a, $b);
code/dynamic_programming/src/longest_common_subsequence/longest_common_subsequence.py
# Part of Cosmos by OpenGenus Foundation def lcs(X, Y): m = len(X) n = len(Y) dp = [[0] * (n + 1) for i in range(m + 1)] for i in range(m + 1): for j in range(n + 1): if i == 0 or j == 0: dp[i][j] = 0 elif X[i - 1] == Y[j - 1]: dp[i][j] = dp[i - 1][j - 1] + 1 else: dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) return dp[m][n] X = "FABCDGH" Y = "AVBDC" # ABC is the longest common subsequence print("Length of LCS = ", lcs(X, Y))
code/dynamic_programming/src/longest_common_subsequence/longest_common_subsequence_rec.java
// Part of Cosmos by OpenGenus Foundation class LongestCommonSubsequenceRec { int lcs( char[] X, char[] Y, int m, int n) { if (m == 0 || n == 0) { // base case return 0; } if (X[m-1] == Y[n-1]) { // if common element is found increase lcs length by 1 return 1 + lcs(X, Y, m-1, n-1); } else { // recursively move back on one string at a time return Math.max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n)); } } public static void main(String[] args) { LongestCommonSubsequenceRec lcs = new LongestCommonSubsequenceRec(); String s1 = "AAGTCGGTAB"; String s2 = "AGXTGXAYTBC"; char[] X=s1.toCharArray(); char[] Y=s2.toCharArray(); int m = X.length; int n = Y.length; System.out.println("Length of LCS is" + " " + lcs.lcs( X, Y, m, n )); } }
code/dynamic_programming/src/longest_common_subsequence_substring/longest_common_subsequence_substring_problem.cpp
// This is a new dynamic programming problem. I have published a research paper // about this problem under the guidance of Professor Rao Li (University of // South Carolina, Aiken) along with my friend. The paper has been accepted by // the Journal of Mathematics and Informatics.The problem is a variation of the // standard longest common subsequence problem. It says that--> "Suppose there // are two strings, X and Y. Now we need to find the longest string, which is a // subsequence of X and a substring of Y." // Link of the paper--> http://www.researchmathsci.org/JMIart/JMI-v25-8.pdf #include <iostream> #include <vector> class LCSubseqSubstr { public: static std::string LCSS(const std::string& X, const std::string& Y, int m, int n, std::vector<std::vector<int>>& W) { int maxLength = 0; // keeps the max length of LCSS int lastIndexOnY = n; // keeps the last index of LCSS in Y W = std::vector<std::vector<int>>(m + 1, std::vector<int>(n + 1, 0)); for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (X[i - 1] == Y[j - 1]) { W[i][j] = W[i - 1][j - 1] + 1; } else { W[i][j] = W[i - 1][j]; } if (W[i][j] > maxLength) { maxLength = W[i][j]; lastIndexOnY = j; } } } return Y.substr(lastIndexOnY - maxLength, maxLength); } }; int main() { std::string X, Y; std::cout << "Input the first string: "; std::getline(std::cin, X); std::cout << "Input the second string: "; std::getline(std::cin, Y); int m = X.length(), n = Y.length(); std::vector<std::vector<int>> W1(m + 1, std::vector<int>(n + 1, 0)); std::cout << "The longest string which is a subsequence of " << X << " and a substring of " << Y << " is " << LCSubseqSubstr::LCSS(X, Y, m, n, W1) << std::endl; std::cout << "The length of the longest string which is a subsequence of " << X << " and a substring of " << Y << " is " << LCSubseqSubstr::LCSS(X, Y, m, n, W1).length() << std::endl; return 0; }
code/dynamic_programming/src/longest_common_substring/Longest_Common_Substring.java
// Space Complexity: O(n) // Time Complexity: O(m*n) import java.util.*; public class Longest_Common_Substring { static String LongestCommonSubstring(String str1, String str2) { String temp; // longest string is str1 and the smallest string is str2 if (str2.length() > str1.length()){ temp = str1; str1 = str2; str2 = temp; } int m = str1.length(); int n = str2.length(); int maxlength = 0; //length of longest common Substring int end = 0; //ending point of longest common Substring int consqRow[][] = new int[2][n + 1]; //store result of 2 consecutive rows int curr = 0; //current row in the matrix //maintaing the array for consequtive two rows for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (str1.charAt(i - 1) == str2.charAt(j - 1)) { consqRow[curr][j] = consqRow[1 - curr][j - 1] + 1; if (consqRow[curr][j] > maxlength) { maxlength = consqRow[curr][j]; end = i - 1; } } else { consqRow[curr][j] = 0; } } curr = 1 - curr; // changing the row alternatively } if (maxlength == 0) { return ""; } else { String s = ""; // string is from end-maxlength+1 to end as maxlength is the length of // the common substring. for (int i = end - maxlength + 1; i <= end; i++) { s += str1.charAt(i); } return s; } } public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.print("Enter String1: "); String string1 = sc.nextLine(); System.out.print("Enter String2: "); String string2 = sc.nextLine(); // function call String temp = LongestCommonSubstring(string1, string2); System.out.println("String1: " + string1 + "\nString2: " + string2 ); if(temp == ""){ System.out.println("No common Substring"); } else System.out.println("Longest Common Substring: "+temp + " (of length: " +temp.length()+")"); } }
code/dynamic_programming/src/longest_common_substring/Longest_Common_Substring.py
def LongestCommonSubstring( string1, string2 ): # longest string is string1 and the smallest string is string2 if len(string2) > len(string1): temp = string2 string2 = string1 string1 = temp m = len(string1) n = len(string2) consqRow = [] for i in range(2): temp = [] for j in range(n + 1): temp.append(0) consqRow.append(temp) curr, maxlength, end = (0, 0, 0) # length of longest common Substring in maxlength # ending point of longest common Substring # maintaing the array for consequtive two rows for i in range(1, m + 1): for j in range(1, n + 1): if string1[i - 1] == string2[j - 1]: consqRow[curr][j] = ( consqRow[1 - curr][j - 1] + 1 ) if consqRow[curr][j] > maxlength: maxlength = consqRow[curr][j] end = i - 1 else: consqRow[curr][j] = 0 curr = 1 - curr # changing the row alternatively if maxlength == 0: return "" else: # string is from end-maxlength+1 to end as maxlength is the length of # the common substring. return string1[end - maxlength + 1 : end + 1] def main(): print("Enter String1: ") string1 = input() print("Enter String2: ") string2 = input() print("String1:", string1) print("String2:", string2) common = LongestCommonSubstring(string1, string2) if common == "": print("No common SubString") else: print( "Longest Common Substring:", common, "( of length:", len(common), ")", ) if __name__ == "__main__": main()
code/dynamic_programming/src/longest_common_substring/Longest_Common_Substring_rename.cpp
// Space Complexity: O(n) // Time Complexity: O(m*n) #include <iostream> #include <vector> std::string LongestCommonSubstring(std::string string1, std::string string2) { std::string temp; // longest string is string1 and the smallest string is string2 if (string2.size() > string1.size()) { temp = string1; string1 = string2; string2 = temp; } int m = string1.size(); int n = string2.size(); int maxLength = 0; // length of longest common Substring int end; // ending point of longest common Substring int curr = 0; // current row in the matrix std::vector<std::vector<int>> consecutiveRows(2, std::vector<int>(n + 1, 0)); // store result of 2 consecutive rows // maintaing the array for consequtive two rows for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (string1[i - 1] == string2[j - 1]) { consecutiveRows[curr][j] = consecutiveRows[1 - curr][j - 1] + 1; if (consecutiveRows[curr][j] > maxLength) { maxLength = consecutiveRows[curr][j]; end = i - 1; } } else consecutiveRows[curr][j] = 0; } curr = 1 - curr; // changing the row alternatively } if (maxLength == 0) return ""; else { std::string s = ""; // string is from end-maxLength+1 to end as maxLength is the length of // the common substring. for (int i = end - maxLength + 1; i <= end; i++) s += string1[i]; return s; } } int main() { std::string string1; std::string string2; std::cout << "Enter String1: "; std::cin >> string1; std::cout << "Enter String2: "; std::cin >> string2; std::cout << "String1: " << string1 << "\nString2: " << string2 << "\n"; std::string lcsStr = LongestCommonSubstring(string1, string2); if (lcsStr == "") std::cout << "No common substring\n"; else std::cout << "Longest Common Substring: " << lcsStr << " (of length: " << lcsStr.size() << ")\n"; return 0; }
code/dynamic_programming/src/longest_common_substring/longest_common_substring_2.cpp
/* * Part of Cosmos by OpenGenus Foundation * finding longest common substring between two strings by dynamic programming */ #include <string> #include <iostream> #include <cstring> using namespace std; int longestCommonSubString(string s1, string s2) { int T[600][600]; //array length can be adjusted by string length of vector can be used memset(T, 0, sizeof(T)); //intialising T to zero int maximum = 0; //filling by recurrence relation for (int i = 1; i <= (int)s1.length(); i++) { for (int j = 1; j <= (int)s2.length(); j++) if (s1[i - 1] == s2[j - 1]) //matching of characters { T[i][j] = T[i - 1][j - 1] + 1; if (maximum < T[i][j]) maximum = T[i][j]; } } return maximum; } //longest common substring int main() { string s1, s2; //standard input stream //cin >> s1 >> s2; s1 = "abcdedwwop"; s2 = "abeeedcedwcdedop"; int maximum = longestCommonSubString(s1, s2); cout << "Length of longest substring = "; cout << maximum << "\n"; //maximum length substring above -- "cded" -- length = 4 }
code/dynamic_programming/src/longest_increasing_subsequence/README.md
# Longest Increasing Subsequence ## Description Given an array of integers `A`, find the length of the longest subsequence such that all the elements in the subsequence are sorted in increasing order. Examples: The lenght of LIS for `{3, 10, 2, 1, 20}` is 3, that is `{3, 10, 20}`. The lenght of LIS for `{10, 22, 9, 33, 21, 50, 41, 60, 80}` is 6, that is `{10, 22, 33, 50, 60, 80}`. ## Solution Let's define a function `f(n)` as the longest increasing subsequence that can be obtained ending in `A[n]`. For each `i` such that `i < n`, if `A[i] < A[n]`, we can add `A[n]` to the longest incresing subsequence that ends in `A[i]`, generating a subsequence of size `1 + f(i)`. This gives us the following optimal substructure: ``` f(0) = 1 // base case f(n) = max(1 + f(i), i < n && A[i] < A[n]) ``` Using memoization or tabulation to store the results of the subproblems, the time complexity of above approach is `O(n^2)`. --- <p align="center"> A massive collaborative effort by <a href="https://github.com/opengenus/cosmos">OpenGenus Foundation</a> </p> ---
code/dynamic_programming/src/longest_increasing_subsequence/longest_increasing_subsequence.c
/* Part of Cosmos by OpenGenus Foundation */ // LIS implementation in C #include<stdio.h> // Max function int max(int a, int b) { return (a > b ? a : b); } // O(n^2) approach int lis(int arr[], int n) { int dp[n], ans = 0 , i = 0, j = 0; for (i = 0; i < n; ++i) { dp[i] = 1; for (j = 0; j < i; j++) if(arr[j] < arr[i]) dp[i] = max(dp[i], 1 + dp[j]); ans = max(ans, dp[i]); } return (ans); } int main() { int arr[] = {10, 22, 9, 33, 21, 50, 41, 60}; int n = sizeof(arr) / sizeof(arr[0]); printf("LIS is : %d\n",lis(arr, n)); return (0); }
code/dynamic_programming/src/longest_increasing_subsequence/longest_increasing_subsequence.cpp
/* Part of Cosmos by OpenGenus Foundation */ #include <iostream> #include <vector> #include <algorithm> using namespace std; // Bottom-up O(n^2) approach int lis(int v[], int n) { int dp[n], ans = 0; for (int i = 0; i < n; ++i) { dp[i] = 1; for (int j = 0; j < i; ++j) if (v[j] < v[i]) dp[i] = max(dp[i], 1 + dp[j]); ans = max(ans, dp[i]); } return ans; } // Bottom-up O(n*log(n)) approach int lis2(int v[], int n) { // tail[i] stores the value of the lower possible value // of the last element in a increasing sequence of size i vector<int> tail; for (int i = 0; i < n; ++i) { vector<int>::iterator it = lower_bound(tail.begin(), tail.end(), v[i]); if (it == tail.end()) tail.push_back(v[i]); else *it = v[i]; } return tail.size(); } int main() { int v[9] = {10, 22, 9, 33, 21, 50, 41, 60, 80}; cout << lis(v, 9) << ", " << lis2(v, 9) << '\n'; return 0; }
code/dynamic_programming/src/longest_increasing_subsequence/longest_increasing_subsequence.go
/* Part of Cosmos by OpenGenus Foundation */ package main import "fmt" /* Expteced output The length of longest_increasing_subsequece in [10 23 5 81 36 37 12 38 51 92] is 7 */ func max(n1, n2 int) int { if n1 > n2 { return n1 } return n2 } //O(n^2) approach func LIS(data []int) int { dp := make([]int, len(data)) ans := 0 for i := range data { dp[i] = 1 for j := 0; j < i; j++ { if data[j] < data[i] { dp[i] = max(dp[i], dp[j]+1) } } ans = max(ans, dp[i]) } return ans } //O(n*logn) approach func LISV2(data []int) int { tail := make([]int, 0) var find int for i := range data { find = -1 //lower bound, we search from back to head for v := range tail { if tail[len(tail)-v-1] > data[i] { find = len(tail) - 1 - v } } if find == -1 { tail = append(tail, data[i]) } else { tail[find] = data[i] } } return len(tail) } func main() { input := []int{10, 23, 5, 81, 36, 37, 12, 38, 51, 92} ans := LIS(input) fmt.Printf("The length of longest_increasing_subsequece in %v is %d\n", input, ans) ans = LISV2(input) fmt.Printf("The length of longest_increasing_subsequece in %v is %d\n", input, ans) }
code/dynamic_programming/src/longest_increasing_subsequence/longest_increasing_subsequence.java
/* Part of Cosmos by OpenGenus Foundation */ import java.lang.Math; class LIS { // returns size of the longest increasing subsequence within the given array // O(n^2) approach static int lis(int arr[], int n) { int dp[] = new int[n]; int ans = 0; for(int i=0; i<n; i++) { dp[i] = 1; for(int j=0; j<i; j++) { if(arr[j] < arr[i]) { dp[i] = Math.max(dp[i], 1+dp[j]); } } ans = Math.max(ans, dp[i]); } return ans; } public static void main (String[] args) throws java.lang.Exception { int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60, 80 }; int n = arr.length; System.out.println("Length of lis is " + lis( arr, n ) + "\n" ); } }
code/dynamic_programming/src/longest_increasing_subsequence/longest_increasing_subsequence.js
/** * Part of Cosmos by OpenGenus Foundation */ /** * Method that returns the length of the Longest Increasing Subsequence for the input array * @param {array} inputArray */ function longestIncreasingSubsequence(inputArray) { // Get the length of the array let arrLength = inputArray.length; let i, j; let subsequenceLengthArray = []; for (i = 0; i < arrLength; i++) { subsequenceLengthArray[i] = 1; } for (i = 1; i < arrLength; i++) { for (j = 0; j < i; j++) if ( inputArray[j] < inputArray[i] && subsequenceLengthArray[j] + 1 > subsequenceLengthArray[i] ) { subsequenceLengthArray[i] = subsequenceLengthArray[j] + 1; } } return Math.max(...subsequenceLengthArray); } console.log( `Longest Increasing Subsequence Length - ${longestIncreasingSubsequence([ 10, 22, 9, 33, 21, 50, 41, 60, 80 ])}` );
code/dynamic_programming/src/longest_increasing_subsequence/longest_increasing_subsequence.py
"""LIS implementation in Python""" # Part of Cosmos by OpenGenus Foundation # Time Complexity: O(nlogn) def length_of_lis(nums): """Return the length of the Longest increasing subsequence""" tails = [0] * len(nums) size = 0 for x in nums: i, j = 0, size while i != j: m = int((i + j) / 2) if tails[m] < x: i = m + 1 else: j = m tails[i] = x size = max(i + 1, size) return size
code/dynamic_programming/src/longest_increasing_subsequence/longest_increasing_subsequence_using_segment_tree.cpp
/* Part of Cosmos by OpenGenus Foundation */ // Finding the Longest Increasing Subsequence using Segment Tree #include <iostream> #include <algorithm> #include <vector> #include <cstring> #include <cmath> using namespace std; // function to compare two pairs int compare(pair<int, int> p1, pair<int, int> p2) { if (p1.first == p2.first) return p1.second > p2.second; return p1.first < p2.first; } // Building the entire Segment tree, the root of which contains the length of the LIS void buildTree(int* tree, int pos, int low, int high, int index, int val) { if (index < low || index > high) return; if (low == high) { tree[pos] = val; return; } int mid = (high + low) / 2; buildTree(tree, 2 * pos + 1, low, mid, index, val); buildTree(tree, 2 * pos + 2, mid + 1, high, index, val); tree[pos] = max(tree[2 * pos + 1], tree[2 * pos + 2]); } // Function to query the Segment tree and return the value for a given range int findMax(int* tree, int pos, int low, int high, int start, int end) { if (low >= start && high <= end) return tree[pos]; if (start > high || end < low) return 0; int mid = (high + low) / 2; return max(findMax(tree, 2 * pos + 1, low, mid, start, end), findMax(tree, 2 * pos + 2, mid + 1, high, start, end)); } int findLIS(int arr[], int n) { pair<int, int> p[n]; for (int i = 0; i < n; i++) { p[i].first = arr[i]; p[i].second = i; } sort(p, p + n, compare); int len = pow(2, (int)(ceil(sqrt(n))) + 1) - 1; int tree[len]; memset(tree, 0, sizeof(tree)); for (int i = 0; i < n; i++) buildTree(tree, 0, 0, n - 1, p[i].second, findMax(tree, 0, 0, n - 1, 0, p[i].second) + 1); return tree[0]; } int main() { int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Length of the LIS: " << findLIS(arr, n); return 0; } // Time Complexity: O(nlogn) // Space Complexity: O(nlogn)
code/dynamic_programming/src/longest_independent_set/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter Collaborative effort by [OpenGenus](https://github.com/opengenus)
code/dynamic_programming/src/longest_palindromic_sequence/README.md
# Longest Palindromic Sequence ## Description Given a string `S`, find the length of the longest subsequence of `S` that is also a palindrome. Examples: The length of the longest palindromic sequence of `bbabcbcab` is 7 (`babcbab` or `bacbcab`). The length of the longest palindromic sequence of `abbaab` is 4 (`abba` or `baab`). ## Solution We can model the state of our function as being the start and the end of the string. So let `f(i,j)` be the longest palindromic sequence presented in `S[i:j]`. Comparing the start and the end of `S`, we have two possibilities: - **The characters are equal:** So these characters will make part of the solution and then we will have to find the longest palindrome in `S[i+1:j-1]`. So, the result is `f(i+1, j-1)` added by 1 or 2, depending if `i == j`. - **The characters are different:** In this case, we will have to discard at least one of them. If we discard `S[i]`, the result will be `f(i+1, j)`, and analogously, if we discard `S[j]`, the result will be `f(i, j-1)`. As we want the longest sequence, we take the maximum of these possibilities, resulting in `max( f(i+1, j), f(i, j-1) )`. Following is a general recursive approach: ``` if (i > j) f(i, j) = 0 // invalid range if (S[i] == S[j]) f(i, j) = f(i+1, j-1) + (1 if i == j else 2) else f(i, j) = max( f(i+1, j), f(i, j-1) ) ``` Using memoization to store the subproblems, the time complexity of this algorithm is O(n^2), being n the length of `S`. --- <p align="center"> A massive collaborative effort by <a href=https://github.com/OpenGenus/cosmos>OpenGenus Foundation</a> </p> ---
code/dynamic_programming/src/longest_palindromic_sequence/longest_palindromic_sequence.c
/* * Part of Cosmos by OpenGenus Foundation * @Author: Ayush Garg * @Date: 2017-10-13 23:11:52 * @Last Modified by: Ayush Garg * @Last Modified time: 2017-10-13 23:23:10 */ #include <stdio.h> #include <string.h> #define MAX 1010 int dp[MAX][MAX]; // used to memoize // utility function to get max int max(int a, int b){ return (a>b)?a:b; } /** * Return the longest palindromic subsequence * in s[i...j] in a top-down approach. * Time complexity: O(n^2), n = length of s */ int lps(const char s[], int i, int j) { // if out of range if(i > j) return 0; // if already computed if(dp[i][j] > -1) return dp[i][j]; // if first and last characters are equal if(s[i] == s[j]) { // number of equal characters is 2 if i != j, otherwise 1 int equalCharacters = 2 - (i == j); return dp[i][j] = equalCharacters + lps(s, i+1, j-1); } // if characters are not equal, discard either s[i] or s[j] return dp[i][j] = max( lps(s, i+1, j), lps(s, i, j-1) ); } // helper function int longest_palindrome(const char s[]) { memset(dp, -1, sizeof dp); return lps(s, 0, strlen(s)-1); } int main() { printf("%d\n",longest_palindrome("bbabcbcab")); // 7: babcbab | bacbcab printf("%d\n",longest_palindrome("abbaab")); // 4: abba | baab printf("%d\n",longest_palindrome("opengenus")); // 3: ene | ege | ngn | nen return 0; }
code/dynamic_programming/src/longest_palindromic_sequence/longest_palindromic_sequence.cpp
/* Part of Cosmos by OpenGenus Foundation */ #include <iostream> #include <cstring> using namespace std; const int MAX = 1010; int memo[MAX][MAX]; // used to store subproblems answers /** * Return the longest palindromic subsequence * in s[i...j] in a top-down approach. * Time complexity: O(n^2), n = length of s */ int lps(const string& s, int i, int j) { // if out of range if (i > j) return 0; // if already computed if (memo[i][j] > -1) return memo[i][j]; // if first and last characters are equal if (s[i] == s[j]) { // number of equal characters is 2 if i != j, otherwise 1 int equalCharacters = 2 - (i == j); return memo[i][j] = equalCharacters + lps(s, i + 1, j - 1); } // if characters are not equal, discard either s[i] or s[j] return memo[i][j] = max( lps(s, i + 1, j), lps(s, i, j - 1) ); } // helper function int longest_palindrome(const string& s) { memset(memo, -1, sizeof memo); return lps(s, 0, s.length() - 1); } int main() { cout << longest_palindrome("bbabcbcab") << '\n'; // 7: babcbab | bacbcab cout << longest_palindrome("abbaab") << '\n'; // 4: abba | baab cout << longest_palindrome("opengenus") << '\n'; // 3: ene | ege | ngn | nen return 0; }
code/dynamic_programming/src/longest_palindromic_sequence/longest_palindromic_sequence.js
/* Part of Cosmos by OpenGenus Foundation */ function longest_palindrome(str) { let longest = []; // A table to store results of subproblems // Strings of length 1 are palindrome of lentgh 1 for (let i = 0; i < str.length; i++) { (longest[i] = longest[i] || [])[i] = 1; } for (let cl = 2; cl <= str.length; ++cl) { for (let i = 0; i < str.length - cl + 1; ++i) { let j = i + cl - 1; if (str[i] == str[j] && cl == 2) { longest[i][j] = 2; } else if (str[i] == str[j]) { longest[i][j] = longest[i + 1][j - 1] + 2; } else { longest[i][j] = Math.max(longest[i][j - 1], longest[i + 1][j]); } } } return longest[0][str.length - 1]; } //test [ ["bbabcbcab", 7], // 7: babcbab | bacbcab ["abbaab", 4], // 4: abba | baab ["opengenus", 3] // 3: ene | ege | ngn | nen ].forEach(test => { console.assert(longest_palindrome(test[0]) == test[1]); });
code/dynamic_programming/src/longest_palindromic_sequence/longest_palindromic_sequence.py
# Part of Cosmos by OpenGenus Foundation def longest_palindrome(text): """ Find the maximum length of a palindrome subsequence Dynamic Programming approach on solving the longest palindromic sequence. Time complexity: O(n^2), n = length of text. Args: text: string which will be processed Returns: Integer of maximum palindrome subsequence length """ length = len(text) # create palindromes length list (space O(n)) palindromes_lengths = [1] * length # iterate on each substring character for fgap in range(1, length): # get pre-calculated length pre = palindromes_lengths[fgap] # reversed iteration on each substring character for rgap in reversed(range(0, fgap)): tmp = palindromes_lengths[rgap] if text[fgap] == text[rgap]: # if equal characters, update palindromes_lengths if rgap + 1 > fgap - 1: # if characters are neighbors, palindromes_lengths is 2 palindromes_lengths[rgap] = 2 else: # else they're added to the pre-calculated length palindromes_lengths[rgap] = 2 + pre else: # if first and last characters do not match, try the latter ones palindromes_lengths[rgap] = max( palindromes_lengths[rgap + 1], palindromes_lengths[rgap] ) # update pre-calculated length pre = tmp # return the maximum palindrome length return palindromes_lengths[0] def main(): """ Main routine to test longest_palindrome funtion """ print(longest_palindrome("bbabcbcab")) # 7: babcbab | bacbcab print(longest_palindrome("abbaab")) # 4: abba | baab print(longest_palindrome("opengenus")) # 3: ene | ege | ngn | nen if __name__ == "__main__": main()
code/dynamic_programming/src/longest_palindromic_substring/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter Collaborative effort by [OpenGenus](https://github.com/opengenus)
code/dynamic_programming/src/longest_palindromic_substring/longest_palindromic_substring.cpp
/* Part of Cosmos by OpenGenus Foundation */ #include <iostream> #include <string> using namespace std; int longestPalSubstr(string str) { int n = str.size(); bool ispal[n][n]; for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) ispal[i][j] = false; // All substrings of length 1 are palindromes int maxLength = 1; for (int i = 0; i < n; ++i) ispal[i][i] = true; // check for sub-string of length 2. for (int i = 0; i < n - 1; ++i) if (str[i] == str[i + 1]) { ispal[i][i + 1] = true; maxLength = 2; } // Check for lengths greater than 2. k is length // of substring for (int k = 3; k <= n; ++k) for (int i = 0; i < n - k + 1; ++i) { // Get the ending index of substring from // starting index i and length k int j = i + k - 1; if (ispal[i + 1][j - 1] && str[i] == str[j]) { ispal[i][j] = true; if (k > maxLength) maxLength = k; } } return maxLength; } int main() { string str = "hacktoberfestsefrisawesome"; cout << "Length of longest palindromic substring is " << longestPalSubstr(str); return 0; }
code/dynamic_programming/src/longest_palindromic_substring/longest_palindromic_substring.py
def longest_pal(test_num): num = str(test_num) # booleanArray with [start][end] pal_boolean_array = [[False for e in range(len(num))] for s in range(len(num))] # all one-letter substrings are palindromes for s in range(len(num)): # length one substrings are all palindromes pal_boolean_array[s][s] = True longest = 1 for s in range(len(num) - 1): # check substrings of length 2 palindrome_boolean = num[s] == num[s + 1] pal_boolean_array[s][s + 1] = palindrome_boolean if palindrome_boolean: longest = 2 for lengths_to_check in range(3, len(num) + 1): # lengths greater than 2 for s in range(len(num) - lengths_to_check + 1): other_characters_symmetry = pal_boolean_array[s + 1][ s + lengths_to_check - 2 ] palindrome_boolean = ( num[s] == num[s + lengths_to_check - 1] and other_characters_symmetry ) pal_boolean_array[s][s + lengths_to_check - 1] = palindrome_boolean if palindrome_boolean: longest = max(longest, lengths_to_check) return longest
code/dynamic_programming/src/longest_repeating_subsequence/longest_repeating_subsequence.cpp
// Part of Cosmos by OpenGenus Foundation //dynamic programming || Longest repeating subsequence #include <iostream> #include <string> #include <vector> int longestRepeatingSubsequence(std::string s) { int n = s.size(); // Obtaining the length of the string std::vector<std::vector<int>>dp(n + 1, std::vector<int>(n + 1, 0)); // Implementation is very similar to Longest Common Subsequence problem for (int x = 1; x <= n; ++x) for (int y = 1; y <= n; ++y) { if (s[x - 1] == s[y - 1] && x != y) dp[x][y] = 1 + dp[x - 1][y - 1]; else dp[x][y] = std::max(dp[x - 1][y], dp[x][y - 1]); } // Returning the value of the result return dp[n][n]; }
code/dynamic_programming/src/matrix_chain_multiplication/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter Collaborative effort by [OpenGenus](https://github.com/opengenus)
code/dynamic_programming/src/matrix_chain_multiplication/matrix_chain_multiplication.c
/* Part of Cosmos by OpenGenus Foundation */ #include <stdio.h> #define inf_ll 2000000000000000000LL #define inf 1000000000 #define eps 1e-8 #define mod 1000000007 #define ff first #define ss second #define N 3456789 typedef long long int ll; ll dp[987][987]; ll ar[N]; /* Matrix Chain Multiplication Problem You are given N matrices A_1, A_2, A_3 .... A_N. You need to find product (A_1 * A_2 * A_3 .... A_N) As matrix product is associative, there can be different ways of computing the same product. For example (A*B*C*D) can be computed as (((A*B)*C)*D) or ((A*B)*(C*D)). The cost of multiplying two matrices X and Y is given by the number of integer multiplications which we need to perform while multiplying them. Among all possible ways of multiplying the given matrices and arriving at the same product, print the minimum total integer multiplications which we need to perform. Input Format - The first line contains number of matrices N The second line contains N+1 integers B_0, B_1, B_2 ..... B_N. The dimensions of matrix A_i is given by B_(i-1)*B_i. for every i between 1 and N Output Format - Print on a single line the answer to the above problem Constraints - 1 <= N <= 500 1 <= B_i <= 10000 for every i between 0 and N Example - Input - 4 5 5 5 5 1 Output - 75 Explanation - Minimum cost is achieved by multiplying matrices in the following order (A_1*(A_2*(A_3*A_4))). In this order, the cost of each matrix multiplication is 25. */ ll min (ll x, ll y) { return x < y ? x : y; } int main () { ll n, len, i, j, k; scanf("%lld", &n); n += 1; for (i = 0; i < n; i++) scanf("%lld", &ar[i]); for (len = 2; len < n; len++) { // Loop on the length of the subproblem for (i = 1; i < n - len + 1; i++) { // Loop on the starting index of subproblem j = i + len - 1; dp[i][j] = inf_ll; for (k = i; k < j; k++) { // Finding the optimal solution for dp[i][j] dp[i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j] + ar[i-1] * ar[k] * ar[j]); } } } printf("%lld\n", dp[1][n-1]); return 0; }
code/dynamic_programming/src/matrix_chain_multiplication/matrix_chain_multiplication.cpp
#include <climits> #include <cstdio> using namespace std; // Part of Cosmos by OpenGenus Foundation // Matrix Ai has dimension p[i-1] x p[i] for i = 1..n int MatrixChainOrder(int p[], int n) { /* For simplicity of the program, one extra row and one * extra column are allocated in m[][]. 0th row and 0th * column of m[][] are not used */ int m[n][n]; int i, j, k, L, q; /* m[i,j] = Minimum number of scalar multiplications needed * to compute the matrix A[i]A[i+1]...A[j] = A[i..j] where * dimension of A[i] is p[i-1] x p[i] */ // cost is zero when multiplying one matrix. for (i = 1; i < n; i++) m[i][i] = 0; // L is chain length. for (L = 2; L < n; L++) for (i = 1; i < n - L + 1; i++) { j = i + L - 1; m[i][j] = INT_MAX; for (k = i; k <= j - 1; k++) { // q = cost/scalar multiplications q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]; if (q < m[i][j]) m[i][j] = q; } } return m[1][n - 1]; } int main() { int arr[] = {1, 2, 3, 4}; int size = sizeof(arr) / sizeof(arr[0]); printf("Minimum number of multiplications is %d ", MatrixChainOrder(arr, size)); getchar(); return 0; }
code/dynamic_programming/src/matrix_chain_multiplication/matrix_chain_multiplication.py
# Part of Cosmos by OpenGenus Foundation # Dynamic Programming Python implementation of Matrix Chain Multiplication. import sys import numpy as np # Matrix Ai has dimension p[i-1] x p[i] for i = 1..n def MatrixChainOrder(p, n): m = [[0 for x in range(n)] for x in range(n)] for i in range(1, n): m[i][i] = 0 for L in range(2, n): for i in range(1, n - L + 1): j = i + L - 1 m[i][j] = sys.maxint for k in range(i, j): q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j] if q < m[i][j]: m[i][j] = q return m[1][n - 1] arr = [1, 2, 3, 4] size = len(arr) print("Minimum number of multiplications is " + str(MatrixChainOrder(arr, size))) # This Code is contributed by Debajyoti Halder in the repo
code/dynamic_programming/src/matrix_chain_multiplication/matrixchainmultiplication.java
// Dynamic Programming Python implementation of Matrix // Chain Multiplication. // Part of Cosmos by OpenGenus Foundation class MatrixChainMultiplication { // Matrix Ai has dimension p[i-1] x p[i] for i = 1..n static int MatrixChainOrder(int p[], int n) { /* For simplicity of the program, one extra row and one extra column are allocated in m[][]. 0th row and 0th column of m[][] are not used */ int m[][] = new int[n][n]; int i, j, k, L, q; /* m[i,j] = Minimum number of scalar multiplications needed to compute the matrix A[i]A[i+1]...A[j] = A[i..j] where dimension of A[i] is p[i-1] x p[i] */ // cost is zero when multiplying one matrix. for (i = 1; i < n; i++) m[i][i] = 0; // L is chain length. for (L=2; L<n; L++) { for (i=1; i<n-L+1; i++) { j = i+L-1; if(j == n) continue; m[i][j] = Integer.MAX_VALUE; for (k=i; k<=j-1; k++) { // q = cost/scalar multiplications q = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j]; if (q < m[i][j]) m[i][j] = q; } } } return m[1][n-1]; } // Driver program to test above function public static void main(String args[]) { int arr[] = new int[] {1, 2, 3, 4}; int size = arr.length; System.out.println("Minimum number of multiplications is "+ MatrixChainOrder(arr, size)); } }
code/dynamic_programming/src/maximum_product_subarray/maximum_product_subarray.cpp
/* Read Problem Description Here - https://leetcode.com/problems/maximum-product-subarray/ Test Cases - Input: [2,3,-2,4] Output: 6 Input: [-2,0,-1] Output: 0 */ #include<iostream> #include<climits> using namespace std; int maxProdSub(int* arr, int n) { int positiveProd = 1, negativeProd = 1; int ans = INT_MIN; for(int i = 0 ; i < n ; i++) { int extraPositive = max(positiveProd * arr[i], max(negativeProd * arr[i], arr[i])); // dummy variable for getting the current max int extraNegative = min(positiveProd * arr[i], min(negativeProd * arr[i], arr[i])); // dummy variable for getting the current min positiveProd = extraPositive; // save current max negativeProd = extraNegative; // save current min if(ans < positiveProd) // if global ans is lesser than current answer, save ans = positiveProd; if(arr[i] == 0) // if 0 is encountered we reset the values of max and min { positiveProd = 1; negativeProd = 1; } } return ans; } int main() { int n; // size input cin>>n; int arr[n]; // array input for(int i = 0 ; i < n ; i++) cin>>arr[i]; cout<<maxProdSub(arr, n); }
code/dynamic_programming/src/maximum_subarray_sum/maximum_subarray_sum.cpp
#include <bits/stdc++.h> using namespace std; int maxSubArraySum(int a[], int size) { // kedane algorithm int max_sum = INT_MIN, current_sum = 0; for (int i = 0; i < size; i++) { current_sum = current_sum + a[i]; if (max_sum < current_sum) max_sum = current_sum; if (current_sum < 0) current_sum = 0; } return max_sum; } // Driver program to test maxSubArraySum int main() { int a[] = {-2, -2, 5, -1, -3, 1, 7, -3}; int n = sizeof(a) / sizeof(a[0]); int max_sum = maxSubArraySum(a, n); cout << "Maximum contiguous sum is " << max_sum; return 0; } /*---------------------------------------------------------------------------------------------------------------------------------------*/ // Time complexity: O(n) // space complexity: O(1)
code/dynamic_programming/src/maximum_sum_increasing_subsequence/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter Collaborative effort by [OpenGenus](https://github.com/opengenus)
code/dynamic_programming/src/maximum_sum_increasing_subsequence/maximum_sum_increasing_subsequence.c
/* Part of Cosmos by OpenGenus Foundation */ #include <stdio.h> int maxSum(int arr[], int n) { int i, j, max = 0; int MSis[n]; for (i = 0; i <= n; i++) MSis[i] = arr[i]; /* Compute maximum sum values in bottom up manner */ for (i = 1; i < n; i++) for(j = 0; j < i; j++) if(arr[j] < arr[i] && MSis[i] < MSis[j] + arr[i]) MSis[i] = MSis[j] + arr[i]; /*Find the max value of array MSis */ for (i = 0; i < n; i++) if (max < MSis[i]) max = MSis[i]; return (max); } int main() { int arr[] = {4, 6, 1, 3, 8, 4, 6}; int n = sizeof(arr) / sizeof(arr[0]); printf("Sum of maximum sum increasing subsequence is %d \n", maxSum(arr, n)); return (0); }
code/dynamic_programming/src/maximum_sum_increasing_subsequence/maximum_sum_increasing_subsequence.cpp
#include <bits/stdc++.h> #include <vector> using namespace std; int maxSum(int arr[], int n){ int i, j, max = 0; vector<int> dp(n); for (i = 0; i < n; i++){ dp[i] = arr[i]; } for (i = 1; i < n; i++ ){ for (j = 0; j < i; j++ ){ if (arr[i] > arr[j] && dp[i] < dp[j] + arr[i]){ dp[i] = dp[j] + arr[i]; } } } for (i = 0; i < n; i++){ if (max < dp[i]){ max = dp[i]; } } return max; } // Driver Code int main() { int arr[] = {4, 6, 1, 3, 8, 4, 6}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Sum of maximum sum increasing subsequence is " << maxSum(arr, n) << ".\n"; return (0); }
code/dynamic_programming/src/maximum_sum_sub_matrix/maximum_sum_sub_matrix.cpp
// Part of Cosmos by OpenGenus Foundation // Author: Karan Chawla // 15th Oct '17 #include <iostream> #include <vector> #include <climits> using namespace std; //Utility function to apply kadane's algorithm //Returns the maximum sub in an array int kadane(vector<int> &nums, int &start) { //Initialize variables int sum = 0; int max_sum = INT_MAX; int finish = -1; int local_start = 0; for (size_t i = 0; i < nums.size(); i++) { sum += nums[i]; if (sum < 0) { sum = 0; local_start = i + 1; } else if (sum > max_sum) { max_sum = sum; start = local_start; finish = i; } } if (finish == -1) return max_sum; //When all numbers are negative max_sum = nums[0]; start = finish = 0; // Find maximum element in the array for (size_t i = 0; i < nums.size(); i++) if (nums[i] > max_sum) { max_sum = nums[i]; start = finish = i; } return max_sum; } // Function to find maximum sum rectangle void findMaxSum(vector<vector<int>> &matrix) { int row = matrix.size(); int col = matrix[0].size(); int maxSum = INT_MIN; int final_left, final_right, final_bottom, final_top; int left, right, i, sum, start, finish = 0; vector<int> temp(row, 0); for (left = 0; left < col; left++) for (right = left; right < col; right++) { for (i = 0; i < row; i++) temp[i] += matrix[i][right]; sum = kadane(temp, start); if (sum > maxSum) { maxSum = sum; final_left = left; final_right = right; final_top = start; final_bottom = finish; } } cout << "(top, left)" << final_top << " " << final_left; cout << "(bottom, right)" << final_bottom << " " << final_right; cout << "Maximum sum" << maxSum; return; } int main() { vector<vector<int>> nums = {{1, 2, -1, -4, -20}, {-8, -3, 4, 2, 1}, {3, 8, 10, 1, 3}, {-4, -1, 1, 7, -6}}; findMaxSum(nums); return 0; }
code/dynamic_programming/src/maximum_sum_sub_matrix/maximum_sum_sub_matrix.java
/* Part of Cosmos by OpenGenus Foundation */ import java.util.*; import java.lang.*; import java.io.*; /** * Given a 2D array, find the maximum sum subarray in it */ public class MaximumSubMatrixSum { public static void main (String[] args) throws java.lang.Exception { findMaxSubMatrix(new int[][] { {1, 2, -1, -4, -20}, {-8, -3, 4, 2, 1}, {3, 8, 10, 1, 3}, {-4, -1, 1, 7, -6} }); } /** * To find maxSum in 1d array * * return {maxSum, left, right} */ public static int[] kadane(int[] a) { //result[0] == maxSum, result[1] == start, result[2] == end; int[] result = new int[]{Integer.MIN_VALUE, 0, -1}; int currentSum = 0; int localStart = 0; for (int i = 0; i < a.length; i++) { currentSum += a[i]; if (currentSum < 0) { currentSum = 0; localStart = i + 1; } else if (currentSum > result[0]) { result[0] = currentSum; result[1] = localStart; result[2] = i; } } //all numbers in a are negative if (result[2] == -1) { result[0] = 0; for (int i = 0; i < a.length; i++) { if (a[i] > result[0]) { result[0] = a[i]; result[1] = i; result[2] = i; } } } return result; } /** * To find and print maxSum, (left, top),(right, bottom) */ public static void findMaxSubMatrix(int[][] a) { int cols = a[0].length; int rows = a.length; int[] currentResult; int maxSum = Integer.MIN_VALUE; int left = 0; int top = 0; int right = 0; int bottom = 0; for (int leftCol = 0; leftCol < cols; leftCol++) { int[] tmp = new int[rows]; for (int rightCol = leftCol; rightCol < cols; rightCol++) { for (int i = 0; i < rows; i++) { tmp[i] += a[i][rightCol]; } currentResult = kadane(tmp); if (currentResult[0] > maxSum) { maxSum = currentResult[0]; left = leftCol; top = currentResult[1]; right = rightCol; bottom = currentResult[2]; } } } System.out.println("MaxSum: " + maxSum + ", range: [(" + left + ", " + top + ")(" + right + ", " + bottom + ")]"); } }
code/dynamic_programming/src/maximum_weight_independent_set_of_path_graph/maximum_weight_independent_set_of_path_graph.cpp
#include <iostream> using namespace std; int main() { int n; cout << "Enter the number of vertices of the path graph : "; cin >> n; int g[n]; cout << "Enter the vertices of the graph : "; for (int i = 0; i < n; i++) cin >> g[i]; int sol[n + 1]; sol[0] = 0; sol[1] = g[0]; for (int i = 2; i <= n; i++) sol[i] = max(sol[i - 1], sol[i - 2] + g[i - 1]); cout << "The maximum weighted independent set sum is : " << sol[n] << endl; int i = n; cout << "The selected verices are : "; while (i >= 1) { if (sol[i - 1] >= sol[i - 2] + g[i - 1]) i--; else { cout << g[i - 1] << " "; i -= 2; } } return 0; }
code/dynamic_programming/src/min_cost_path/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter Collaborative effort by [OpenGenus](https://github.com/opengenus)
code/dynamic_programming/src/min_cost_path/min_cost_path.c
#include <stdio.h> #define ROWS 3 #define COLUMNS 3 int min(int x, int y, int z) { if (x < y) return ((x < z)? x : z); else return ((y < z)? y : z); } int minCost(int cost[ROWS][COLUMNS], int m, int n) { int i, j; int travellingCost[ROWS][COLUMNS]; travellingCost[0][0] = cost[0][0]; for (i = 1; i <= m; i++) travellingCost[i][0] = travellingCost[i - 1][0] + cost[i][0]; for (j = 1; j <= n; j++) travellingCost[0][j] = travellingCost[0][j - 1] + cost[0][j]; for (i = 1; i <= m; i++) for (j = 1; j <= n; j++) travellingCost[i][j] = min(travellingCost[i - 1][j - 1], travellingCost[i - 1][j], travellingCost[i][j - 1]) + cost[i][j]; return (travellingCost[m][n]); } int main() { int cost[ROWS][COLUMNS] = { {1, 2, 3}, {4, 8, 2}, {1, 5, 3} }; printf("%d \n", minCost(cost, 2, 2)); return (0); }
code/dynamic_programming/src/min_cost_path/min_cost_path.cpp
#include <cstdio> using namespace std; #define R 3 #define C 3 // Part of Cosmos by OpenGenus Foundation int min(int x, int y, int z); int minCost(int cost[R][C], int m, int n) { int i, j; // Instead of following line, we can use int tc[m+1][n+1] or // dynamically allocate memoery to save space. The following line is // used to keep te program simple and make it working on all compilers. int tc[R][C]; tc[0][0] = cost[0][0]; /* Initialize first column of total cost(tc) array */ for (i = 1; i <= m; i++) tc[i][0] = tc[i - 1][0] + cost[i][0]; /* Initialize first row of tc array */ for (j = 1; j <= n; j++) tc[0][j] = tc[0][j - 1] + cost[0][j]; /* Construct rest of the tc array */ for (i = 1; i <= m; i++) for (j = 1; j <= n; j++) tc[i][j] = min(tc[i - 1][j - 1], tc[i - 1][j], tc[i][j - 1]) + cost[i][j]; return tc[m][n]; } int min(int x, int y, int z) { if (x < y) return (x < z) ? x : z; else return (y < z) ? y : z; } int main() { int cost[R][C] = { {1, 2, 3}, {4, 8, 2}, {1, 5, 3} }; printf(" %d ", minCost(cost, 2, 2)); return 0; }
code/dynamic_programming/src/min_cost_path/min_cost_path.java
// Part of Cosmos by OpenGenus Foundation // Given a cost matrix and calculate the minimum cost path to reach (m, n) // from (0, 0) import java.io.*; import java.lang.*; import java.math.*; import java.util.*; class MinCostPath { static int minCost(int costMatrix[][], int m, int n) { int i,j; int tc[][] = new int[m+1][n+1]; tc[0][0] = costMatrix[0][0]; for (i = 1; i <= m; i++) tc[i][0] = tc[i-1][0] + costMatrix[i][0]; for (j = 1; j <= n; j++) tc[0][j] = tc[0][j-1] + costMatrix[0][j]; for (i = 1; i <= m; i++) for (j = 1; j <= n; j++) tc[i][j] = min(tc[i-1][j-1], tc[i-1][j], tc[i][j-1]) + costMatrix[i][j]; return tc[m][n]; } static int min(int x, int y, int z) { if (x < y) return (x < z)? x : z; else return (y < z)? y : z; } public static void main(String args[]) { int cost[][] = new int[][]{ {1, 2, 3}, {4, 8, 2}, {1, 5, 3} }; System.out.println(minCost(cost, 2, 2)); } }
code/dynamic_programming/src/min_cost_path/min_cost_path.py
# Part of Cosmos by OpenGenus Foundation def minCost(costMatrix, m, n, traceback=True): """Given a cost matrix and calculate the minimum cost path to reach (m, n) from (0, 0). """ tc = [[0 for x in range(m + 1)] for y in range(n + 1)] tc[0][0] = costMatrix[0][0] # Initialize first column of total cost array for i in range(1, m + 1): tc[i][0] = tc[i - 1][0] + costMatrix[i][0] # Initialize first row of total cost array for i in range(1, n + 1): tc[0][i] = tc[0][i - 1] + costMatrix[0][i] # Calculate the rest of total cost array for i in range(1, m + 1): for j in range(1, n + 1): tc[i][j] = ( min(tc[i - 1][j - 1], tc[i - 1][j], tc[i][j - 1]) + costMatrix[i][j] ) path = [] if traceback: path.append((m, n)) x, y = m, n while x != 0 and y != 0: prevCost = tc[x][y] - costMatrix[x][y] if x > 0 and prevCost == tc[x - 1][y]: x -= 1 elif y > 0 and prevCost == tc[x][y - 1]: y -= 1 else: x -= 1 y -= 1 path.append((x, y)) path.append((0, 0)) path.reverse() return tc[m][n], path # Example costMatrix = [[1, 2, 3], [4, 8, 2], [1, 5, 3]] print(minCost(costMatrix, 2, 2))
code/dynamic_programming/src/min_rests_skipped_to_reach_on_time/Minimum Skips to Arrive at Meeting On Time.go
import "fmt" func main() { fmt.Println(minTimeToVisitAllPoints([][]int{{1, 1}, {3, 4}, {-1, 0}})) fmt.Println(minTimeToVisitAllPoints([][]int{{3, 2}, {-2, 2}})) } func minTimeToVisitAllPoints(points [][]int) int { n := len(points) if n == 0 { return 0 } dp := make([][]int, n) for i := 0; i < n; i++ { dp[i] = make([]int, n) for j := 0; j < n; j++ { if i == j { dp[i][j] = 0 } else { dp[i][j] = -1 } } } for i := 0; i < n; i++ { dp[i][i] = 0 } for i := 0; i < n-1; i++ { for j := i + 1; j < n; j++ { dp[i][j] = dp[i][j-1] + dist(points[i], points[j]) if dp[i][j] > points[j][0] { dp[i][j] = -1 } } }
code/dynamic_programming/src/min_rests_skipped_to_reach_on_time/Minimum Skips to Arrive at Meeting On Time.java
class DPprob { public int minSkips(int[] A, int s, int target) { int n = A.length, dp[] = new int[n + 1]; for (int i = 0; i < n; ++i) { for (int j = n; j >= 0; --j) { dp[j] += A[i]; if (i < n - 1) dp[j] = (dp[j] + s - 1) / s * s; // take a rest if (j > 0) dp[j] = Math.min(dp[j], dp[j - 1] + A[i]); } } for (int i = 0; i < n; ++i) { if (dp[i] <= (long) s * target) return i; } return -1; } public static void main(String args[]) { /*Example 1: Input: dist = [1,3,2], speed = 4, hoursBefore = 2 Output: 1 Explanation: Without skipping any rests, you will arrive in (1/4 + 3/4) + (3/4 + 1/4) + (2/4) = 2.5 hours. You can skip the first rest to arrive in ((1/4 + 0) + (3/4 + 0)) + (2/4) = 1.5 hours. Note that the second rest is shortened because you finish traveling the second road at an integer hour due to skipping the first rest.*/ int dist1 = {1, 3, 2}; int speed1 = 4; int hoursBefore1 = 2; System.out.println(minSkips(dist1, speed1, hoursBefore1)); } }
code/dynamic_programming/src/min_rests_skipped_to_reach_on_time/Minimum Skips to Arrive at Meeting On Time.py
def minSkips(self, A, s, target): n = len(A) dp = [0] * (n + 1) for i, a in enumerate(A): for j in range(n, -1, -1): dp[j] += a if i < n - 1: dp[j] = (dp[j] + s - 1) / s * s if j: dp[j] = min(dp[j], dp[j - 1] + a) for i in range(n): if dp[i] <= s * target: return i return -1 if __name__ == '__main__': #Input: dist = [1, 3, 2], speed = 4, hoursBefore = 2 #Output: 1 #Explanation: #Without skipping any rests, you will arrive in (1/4 + 3/4) + (3/4 + 1/4) + (2/4) = 2.5 hours. #You can skip the first rest to arrive in ((1/4 + 0) + (3/4 + 0)) + (2/4) = 1.5 hours. #Note that the second rest is shortened because you finish traveling the second road at an integer # #hour due to skipping the first rest. dist1 = [1, 3, 2] speed1 = 4 hoursBefore1 = 2 print(minSkips(minSkips,dist1,speed1,hoursBefore1)-1)#returns 1 #Input: dist = [7, 3, 5, 5], speed = 2, hoursBefore = 10 #Output: 2 #Explanation: #Without skipping any rests, you will arrive in (7/2 + 1/2) + (3/2 + 1/2) + (5/2 + 1/2) + (5/2) = 11.5 hours. #You can skip the first and third rest to arrive in ((7/2 + 0) + (3/2 + 0)) + ((5/2 + 0) + (5/2)) = 10 hours. dist2 = [7, 3, 5, 5] speed2 = 2 hoursBefore2 = 10 print(minSkips(minSkips, dist2, speed2, hoursBefore2)-1)#returns 2 #Input: dist = [7, 3, 5, 5], speed = 1, hoursBefore = 10 #Output: -1 #Explanation: It is impossible to arrive at the meeting on time even if you skip all the rests. dist3 = [7, 3, 5, 5] speed3 = 1 hoursBefore3 = 10 print(minSkips(minSkips, dist3, speed3, hoursBefore3))
code/dynamic_programming/src/min_rests_skipped_to_reach_on_time/README.md
# Minimum Rests Skipped to Reach on Time ## Description You have to travel to your office in `reachTime` time by travelling on `n` roads given as array `dist` where `dist[i]` is the length of ith road. You have a constant speed `Speed`. After you travel road `i`, you must rest and wait for the next integer hour before you can begin traveling on the next road. For example, if traveling a road takes 1.4 hours, you must wait until the 2 hour mark before traveling the next road. If traveling a road takes exactly 2 hours, you do not need to wait. However, you are allowed to skip some rests to be able to arrive on time, meaning you do not need to wait for the next integer hour. Note that this means you may finish traveling future roads at different hour marks. Return the **minimum** number of skips required to arrive at the office on time, or -1 if it is impossible. ## Thought Process Let's number the roads and stops starting from 0. So the stop after road 0 is stop 0 and so on. Thinking in terms of subproblems and recurrence is a good start. Try answering yourself before revealing the collapsed hints. <details> <summary>What's the Subproblem in terms of roads and skips?</summary> What is the minimum time which it takes to cover the i roads using j skips. </details> <details> <summary>What's the recurrence relation?</summary> <p>There are two ways to cover i roads using j skips. <ol> <li> You cover i-1 roads using j skips and don't skip at the i-1 th ie. between roads i-1 and i stop. </li> <li> You cover i roads using j-1 skips and skip after the ith stop. So you use j-1+1 skip. </li> </ol> </p> Now, you just need to think about the edge cases like how you would cover i roads without any skip? </details> ## Solution Create a 2D DP table of n rows and n columns where dp[i][j] stores the minimum time to cover till(including) road i using j skips. To find the answer, we iterate over all columns (times taken) for road n-1. The skip count corresponding to the first time which is lesser than reachTime is the answer.
code/dynamic_programming/src/min_rests_skipped_to_reach_on_time/min_skips.cpp
// Part of Cosmos by OpenGenus Foundation #include<bits/stdc++.h> int minSkips(vector<int>& dist, int speed, int reachTime) { /* dist: array containing lengths of roads speed: the constant speed of travel reachTime: the time before/at which you have to reach the office. You start at time=0. */ int n = dist.size(); double time[n]; // Find times taken to cover the roads. for(int i=0; i<n ; i++) { time[i] = dist[i]*1.0/speed; } // Make a dp table where dp[i][j]=minimum time to cover i roads using j skips double dp[n][n]; memset(dp, 0, sizeof(dp)); /* Note that, while taking ceiling and floor of floats and doubles, we can get precision errors due to inability of computers to represent floating point numbers precisely in memory. This is why we subtract a very small number eps (epsilon) while taking ceiling of float. Eg. ceil(1.0000000001)=2 which is unintended in our case. */ double eps = 0.00000001; // The dp table is going to be a lower triangular matrix as the number // of skips cannot exceed the number of roads. for(int i=0;i<n;i++) { for(int j=0;j<=i;j++) { // cover road 0 with 0 skips if(i == 0 && j == 0) dp[i][j]=time[i]; // no sop is skipped else if (j == 0) dp[i][0] = ceil(dp[i-1][0]- eps)+time[i]; // all the stops are skipped else if (i == j) dp[i][j] = dp[i-1][j-1]+time[i]; // we've used j skips to cover i roads else dp[i][j] = min( ceil (dp[i-1][j] - eps), dp[i-1][j-1]) + time[i]; } } // check the minimum number of skips required to reach on time for(int j=0;j<n;j++) { if( dp[n-1][j] <= reachTime ) return j; } // we cannot reach on time even if we skip all stops. return -1; }
code/dynamic_programming/src/minimum_cost_polygon_triangulation/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter Collaborative effort by [OpenGenus](https://github.com/opengenus)
code/dynamic_programming/src/minimum_insertion_palindrome/minimum_insertions_palindrome_using_lcs.cpp
/* Part of Cosmos by OpenGenus Foundation */ //Number of insertion required to make a string palindrome using dynamic programming #include <cstring> #include <iostream> #include <algorithm> using namespace std; int LCS(char *s, string r, int n, int m) { int d[n + 1][m + 1];//d[i][j] contains length of LCS of s[0..i-1] and r[0..j-1] for (int i = 0; i <= n; i++) for (int j = 0; j <= m; j++) { if (i == 0 || j == 0) d[i][j] = 0; else if (s[i - 1] == r[j - 1]) d[i][j] = d[i - 1][j - 1] + 1; else d[i][j] = max(d[i - 1][j], d[i][j - 1]); } return d[n][m]; } int MinInsertion(char s[], int n) { //Store reverse of given string string rev(s, n); reverse(rev.begin(), rev.end()); return n - LCS(s, rev, n, n); } int main() { char s[] = "abcd"; cout << MinInsertion(s, strlen(s)); return 0; }
code/dynamic_programming/src/newman_conway/newman_conway_dp.cpp
#include <iostream> class NewmanConwaySequence { public: NewmanConwaySequence(unsigned int n) : n(n) {} void calculateNewmanConwaySequenceTermDP(bool flag); private: unsigned int n; }; void NewmanConwaySequence::calculateNewmanConwaySequenceTermDP(bool flag) { if(flag == true) { unsigned int ncs[n + 1]; ncs[0] = 0; ncs[1] = 1; ncs[2] = 1; for (int i = 3; i <= n; i++) ncs[i] = ncs[ncs[i - 1]] + ncs[i - ncs[i - 1]]; std::cout << "\nNewman Conway Sequence with " << n << " elements : "; for(int i = 1; i <= n; i++) std::cout << ncs[i] << " "; } else { unsigned int ncs[n + 1]; ncs[0] = 0; ncs[1] = 1; ncs[2] = 1; for (int i = 3; i <= n; i++) ncs[i] = ncs[ncs[i - 1]] + ncs[i - ncs[i - 1]]; std::cout << "\nNewman Conway Sequence term at " << n << " indexed : "; std::cout << ncs[n]; } } int main() { unsigned int nValue, value; bool flag; std::cout << "\nEnter the Index of Newman Conway Sequence : "; std::cin >> nValue; NewmanConwaySequence aNewmanConwaySequenceoj(nValue); std::cout << "\nEnter the non-zero to generate the Newman Conway Sequence or zero to generate particular term in Newman Conway Sequence : "; std::cin >> value; if(value) flag = true; else flag = false; if(flag == true) aNewmanConwaySequenceoj.calculateNewmanConwaySequenceTermDP(true); else aNewmanConwaySequenceoj.calculateNewmanConwaySequenceTermDP(false); }
code/dynamic_programming/src/no_consec_ones/README.md
# Cosmos ## No Consecutive Ones ### Problem Statement ``` Given a length `n`, determine the number of binary strings of length `n` that have no consecutive ones. For example, for `n=3`, the strings of length `3` that have no consecutive ones are `000,001,010,100,101`, so the algorithm would return `5`. Expected time complexity: `O(2*n)`, where n is the length of the binary string with no consecutive ones. ``` Collaborative effort by [OpenGenus](https://github.com/opengenus)
code/dynamic_programming/src/no_consec_ones/no_consec_1.cpp
#include <iostream> #include <vector> using namespace std; int countNonConsecutiveOnes(int n) { vector<int> endingZero(n), endingOne(n); endingZero[0] = endingOne[0] = 1; for (int i = 1; i < n; i++) { endingZero[i] = endingZero[i - 1] + endingOne[i - 1]; endingOne[i] = endingZero[i - 1]; } return endingZero[n - 1] + endingOne[n - 1]; } int main() { int binaryStringLength; cout << "Enter the length of binary string: "; cin >> binaryStringLength; cout << "\nCount of Binary representations of length " << binaryStringLength << " not having consecutive ones = "; cout << countNonConsecutiveOnes(binaryStringLength) << endl; return 0; }
code/dynamic_programming/src/no_consec_ones/no_consec_ones.py
# Part of Cosmos by Open Genus Foundation # Code contributed by Shamama Zehra # A dynamic programming solution for no Conseuctive Ones in Binary String problem def noConsecOnes(n): a = [0 for x in range(n)] # number of strings ending with 0 b = [0 for x in range(n)] # number of strings ending with 1 a[0], b[0] = 1, 1 for i in range(1, n): # number of strings ending with 0 is the previous ending with 0 # plus the previous ending with 1 with a 0 added a[i] = a[i - 1] + b[i - 1] # number of strings ending with 1 is the previous ones ending with # 0 plus a 0 b[i] = a[i - 1] return a[n - 1] + b[n - 1] # Driver program to test above function print( "Number of binary strings of length 5 with no consecutive ones is " + str(noConsecOnes(5)) )
code/dynamic_programming/src/number_of_dice_rolls_with_target_sum/NumberOfDiceRollsWithTargetSum.java
public class NumberOfDiceRollsWithTargetSum { public static void main(String[] args) { // Test case 1 System.out.println(numRollsToTarget(1, 6, 3)); // it should output 1 // Test case 2 System.out.println(numRollsToTarget(30, 30, 500)); //it should output 222616187 } public static int numRollsToTarget(int dices, int faces, int target) { /* * dp[i][j] = the number of possible ways modulo 10^9+7 * i = the current i-th dice * j = the current number of points is j */ long[][] dp = new long[35][1005]; long MOD = (long)1e9 + 7; for (int i = 1; i <= faces; i++) dp[1][i] = 1; // Initialization assignment for (int i = 2; i <= dices; i++) { for (int j = i; j <= i * faces; j++) { // when j < i, it clearly does not exist. long count = 0; /* * Suppose the current dice i rolls the k-th face, * then it should be transferred from the point when the last dice was j-k * Note that J-K may be less than 1, so we have to limit the range of k */ for (int k = 1; k <= Math.min(faces, j - 1); k++) { count = (count + dp[i - 1][j - k]) % MOD; } dp[i][j] = (dp[i][j] + count) % MOD; } } return (int)dp[dices][target]; } }
code/dynamic_programming/src/number_of_substring_divisible_by_8_but_not_3/README.md
# Number of substrings divisible by 8 but not 3 We are interested to find number of substrings of a given string which are divisible by 8 but not 3. For example, in "556", possible substrings are "5", "6", "55", "56" and "556". Amongst which only 56 is divisible by 8 and is not divisible by 3. Therefore, answer should be 1 This problem can be solved by first finding all the possible substrings of given string and next counting ones relevant to us but this gives us O(n^2) as time complexity. We can use dynamic programming here to get O(n) as time complexity. For more explanation, refer to <a href="https://iq.opengenus.org/number-of-substrings-divisible-by-8-but-not-3/">number_of_substring_divisible_by_8_but_not_3</a>
code/dynamic_programming/src/number_of_substring_divisible_by_8_but_not_3/number_of_substrings.cpp
#include <bits/stdc++.h> using namespace std; int no_of_substr(string str, int len, int k) { int count = 0; // iterate over the string for (int i = 0; i < len; i++) { int n = 0; // consider every substring starting from index 'i' for (int j = i; j < len; j++) { n = n * 10 + (str[j] - '0'); // if substring is divisible by k, increase the counter if (n % k == 0) count++; } } return count; } int main() { string str; int len; cout << "Enter the string: "; cin >> str; len = str.length(); cout << "Desired Count: " << no_of_substr(str, len, 8) - no_of_substr(str, len, 24); return 0; }
code/dynamic_programming/src/numeric_keypad_problem/numeric_keypad_problem.cpp
#include <bits/stdc++.h> using namespace std; vector<vector<int>> nums; void populate() { nums.resize(10); nums[0].push_back(0); nums[0].push_back(8); nums[1].push_back(1); nums[1].push_back(2); nums[1].push_back(4); nums[2].push_back(1); nums[2].push_back(2); nums[2].push_back(3); nums[2].push_back(5); nums[3].push_back(2); nums[3].push_back(3); nums[3].push_back(6); nums[4].push_back(1); nums[4].push_back(4); nums[4].push_back(5); nums[4].push_back(7); nums[5].push_back(2); nums[5].push_back(4); nums[5].push_back(5); nums[5].push_back(6); nums[5].push_back(8); nums[6].push_back(3); nums[6].push_back(5); nums[6].push_back(6); nums[6].push_back(9); nums[7].push_back(4); nums[7].push_back(7); nums[7].push_back(8); nums[8].push_back(0); nums[8].push_back(5); nums[8].push_back(7); nums[8].push_back(8); nums[8].push_back(9); nums[9].push_back(6); nums[9].push_back(8); nums[9].push_back(9); } int main() { int t; cin >> t; populate(); while (t--) { int n; cin >> n; int arr[10][n + 1]; for (int i = 0; i < 10; i++) { arr[i][0] = 0; arr[i][1] = 1; arr[i][2] = nums[i].size(); } for (int i = 3; i <= n; i++) for (int j = 0; j < 10; j++) { arr[j][i] = 0; for (std::size_t k = 0; k < nums[j].size(); k++) arr[j][i] += arr[nums[j][k]][i - 1]; } int count = 0; for (int i = 0; i < 10; i++) count += arr[i][n]; cout << count << endl; } return 0; }
code/dynamic_programming/src/optimal_binary_search_tree/optimal_bst.py
# Given keys and frequency, calculate the most optimal binary search tree that can be created making use of minimum cost keys = list(map(int, input("Enter the list of keys").split())) freq = list(map(int, input("Enter the list of frequencies").split())) z = [] n = len(keys) for i in range(n): z += [[keys[i], freq[i]]] z.sort() cost = [[10 ** 18 for i in range(n)] for j in range(n)] # initialising with infinity for i in range(n): keys[i] = z[i][0] freq[i] = z[i][1] s = [freq[0]] for i in range(n - 1): s += [s[i] + freq[i + 1]] for i in range(n): cost[i][i] = freq[i] for i in range(2, n + 1): for j in range(n - i + 1): l = j r = l + i - 1 for k in range(l, r + 1): if k == l: cost[l][r] = min(cost[l][r], cost[l + 1][r]) elif k == r: cost[l][r] = min(cost[l][r], cost[l][r - 1]) else: cost[l][r] = min(cost[l][r], cost[l][k] + cost[k + 1][r]) cost[l][r] += s[r] - s[l] + freq[l] print("Cost of Optimal BST is : ", cost[0][n - 1])
code/dynamic_programming/src/palindrome_partition/README.md
# Palindrome Partitioning ## Description Given a string `S`, determine the minimum number of cuts necessary to partition `S` in a set of palindromes. For example, for string `aaabbba`, minimum cuts needed is `1`, making `aa | abba`. ## Solution First we need to know for each substring of `S`, whether it is a palindrome or not. Let' denote by `isPalindrome(i, j)` if `S[i:j]` is palindrome. This can be computed in `O(n^2)` by the following optimal substructure: ``` isPalindrome(i, j) = false, if i > j or S[i] != S[j] true, if j - i <= 1 && S[i] == S[j] isPalindrome(i+1, j-1), otherwise ``` Now let's denote by `minPartition(n)` the minimum number of partitions needed to partition `S[0:n]` in a set of palindromes. For each `i` such that `S[i+1:n]` is palindrome, we can partition at position `i`, and the result for `minPartition(n)` would be `1 + minPartition(i)`. Based on this: ``` minPartition(n) = min( 1 + minPartition(i), 0 <= i < n && isPalindrome(i+1, n) ) ``` ## Complexity The time complexity of `isPalindrome` is `O(n^2)`, as there are `n^2` stated that are computed in `O(1)`. The time complexity of `minPartition` is also `O(n^2)`, as there are `n` states that are computes in `O(n)`. Therefore, the overall time complexity of such approach is `O(n^2)`. --- <p align="center"> A massive collaborative effort by <a href="https://github.com/opengenus/cosmos">OpenGenus Foundation</a> </p> ---
code/dynamic_programming/src/palindrome_partition/palindrome_partition.cpp
/* Part of Cosmos by OpenGenus Foundation */ #include <iostream> #include <cstring> #include <string> #define MAX 1010 using namespace std; int isPal[MAX][MAX], memo[MAX]; /* * Checks if s[i...j] is palindrome * in a top-down fashion. Result is * stored in isPal matrix. * Time complexity: O(n^2) */ int isPalindrome(const string &s, int i, int j) { if (i > j) return isPal[i][j] = 0; if (isPal[i][j] > -1) return isPal[i][j]; if (j - i <= 1 && s[i] == s[j]) return isPal[i][j] = 1; if (s[i] == s[j]) return isPal[i][j] = isPalindrome(s, i + 1, j - 1); return isPal[i][j] = 0; } /* * Compute the minimum number of cuts * necessary to partition the string * s[0...i] in a set of palindromes. * Time complexity: O(n^2) */ int minPalPartition(const string &s, int i) { if (isPal[0][i]) return memo[i] = 0; if (memo[i] > -1) return memo[i]; int ans = i + 1; for (int j = 0; j < i; ++j) if (isPal[j + 1][i] == 1) ans = min(ans, 1 + minPalPartition(s, j)); return memo[i] = ans; } // Helper function int solve(const string &s) { memset(isPal, -1, sizeof isPal); memset(memo, -1, sizeof memo); int n = s.length(); for (int i = 0; i < n; ++i) for (int j = i; j < n; ++j) isPalindrome(s, i, j); return minPalPartition(s, n - 1); } int main() { cout << solve("aaabba") << '\n'; // 1: aa | abba cout << solve("ababbbabbababa") << '\n'; // 3: a | babbbab | b | ababa return 0; }
code/dynamic_programming/src/palindrome_partition/palindrome_partition.js
/** * Part of Cosmos by OpenGenus Foundation */ /** * Method which returns the Minimum Cuts to perform Palindrome Partioning * @param {string} inputString */ function palindromePartioning(inputString) { // Get the length of the string let strLength = inputString.length; let minCuts = 0; let i, L, j; /* Create two arrays to build the solution in bottom up manner cutMatrix = Minimum number of cuts needed for palindrome partitioning of substring inputString[0..i] palMatrix = true if substring inputString[i..j] is palindrome, else false */ let palMatrix = []; let cutMatrix = []; // for single letter palindromes set them true (since they palindrome on there own) for (i = 0; i < strLength; i++) { // lazy initialize the element of 2d array if (!palMatrix[i]) palMatrix[i] = []; palMatrix[i][i] = true; } /* L is substring length. Build the solution in bottom up manner by considering all substrings of length starting from 2 to n. */ for (L = 2; L <= strLength; L++) { // For substring of length L, set different possible starting indexes for (i = 0; i < strLength - L + 1; i++) { j = i + L - 1; // Set ending index // If L is 2, then we just need to compare two characters. Else // need to check two corner characters and value of palMatrix[i+1][j-1] if (L == 2) { if (!palMatrix[i]) palMatrix[i] = []; palMatrix[i][j] = inputString[i] == inputString[j]; } else { if (!palMatrix[i]) palMatrix[i] = []; palMatrix[i][j] = inputString[i] == inputString[j] && palMatrix[i + 1][j - 1]; } } } for (i = 0; i < strLength; i++) { if (palMatrix[0][i] == true) cutMatrix[i] = 0; else { cutMatrix[i] = strLength; for (j = 0; j < i; j++) { if (palMatrix[j + 1][i] == true && 1 + cutMatrix[j] < cutMatrix[i]) cutMatrix[i] = 1 + cutMatrix[j]; } } } // Return the min cut value for complete string. return cutMatrix[strLength - 1]; } console.log( `Minimum Cuts to perform Palindrome Partioning - ${palindromePartioning( "hallelujah" )}` );
code/dynamic_programming/src/rod_cutting/README.md
# Rod Cutting Given a rod of length n units and an array of prices p<sub>i</sub> for rods of length i = 1, 2, . . . ,n. Determine the maximum revenue r <sub>n</sub> obtainable by cutting the rod and selling the pieces. ## Explanation Let the table of prices be - length (i) | 1|2|3|4|5|6|7|8|9|10 -----------|--|-|-|-|-|--|-|--|--|------------ price (p<sub>i</sub>)|1|5|8|9|10|17|17|20|24|30 For a rod of length n = 4 ![Eight ways of cutting rod of length 4](https://www.cs.indiana.edu/~achauhan/Teaching/B403/LectureNotes/images/07-rodcutting-example.jpg) > Image credits: ([CS Indiana](https://www.cs.indiana.edu/~achauhan/Teaching/B403/LectureNotes/images/07-rodcutting-example.jpg)) ![Thought Process](https://cdn-images-1.medium.com/max/1400/1*b7bv3tR9kUrcVtvWeXFv4A.png) > Image credits: ([Medium: Pratik Anand](https://medium.com/@pratikone/dynamic-programming-for-the-confused-rod-cutting-problem-588892796840)) Maximum revenue is obtained by cutting the rod into two pieces each of length 2. Thus, maximum revenue obtained is 10. This problem satisfies both properties of Dynamic programming and can be solved by the following recurrence relation. ### Recurrence Relation ![Recurrence Relation](https://camo.githubusercontent.com/56668b0cbfac4b80697e6d03d03b54436ca047db/68747470733a2f2f6c617465782e636f6465636f67732e636f6d2f6769662e6c617465783f725f6e2533446d6178253238705f692532302b253230725f2537426e2d31253744253239253230253543746578742537422532307768657265253230253744253230312532302535436c65253230692532302535436c652532306e) ## Complexity Time complexity : O(n^2) Space complexity : O(n) --- <p align="center"> A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a> </p> ---
code/dynamic_programming/src/rod_cutting/rod_cutting.c
#include <stdio.h> #define INT_MIN -32767 #define max(a, b) (((a) > (b)) ? (a) : (b)) int cutRod(int price[], int length_of_rod) { if (length_of_rod <= 0) return (0); int max_val = INT_MIN, i; for (i = 0; i < length_of_rod; i++) max_val = max(max_val, price[i] + cutRod(price, length_of_rod - i - 1)); return (max_val); } int main() { int length_of_rod; printf("Enter length of rod: "); scanf("%d", &length_of_rod); int price[length_of_rod], i; printf("Enter prices: \n"); for (i = 0; i < length_of_rod; i++) scanf("%d", &price[i]); printf("Maximum Obtainable Value is %d \n", cutRod(price, length_of_rod)); return (0); }
code/dynamic_programming/src/rod_cutting/rod_cutting.cpp
#include <iostream> #include <vector> // Part of Cosmos by OpenGenus Foundation // Use bottom-up DP, O(n^2) time, O(n) space. using namespace std; int rodCutting(int rod_length, vector<int> prices) { vector<int> best_price(rod_length + 1, 0); best_price[0] = 0; for (int i = 1; i <= rod_length; ++i) { int maximum_price = INT8_MIN; for (int j = 1; j <= i; ++j) maximum_price = max(maximum_price, prices[j - 1] + best_price[i - j]); best_price[i] = maximum_price; } return best_price[rod_length]; } int main() { cout << rodCutting(8, {1, 5, 8, 9, 10, 17, 17, 20, 24, 30}) << endl; // should be 22 (one length 2, another length 6) cout << rodCutting(10, {1, 5, 8, 9, 10, 17, 17, 20, 24, 30}) << endl; // should be 30 return 0; }
code/dynamic_programming/src/rod_cutting/rod_cutting.go
// Part of Cosmos by OpenGenus Foundation // Code contributed by Marc Tibbs // A Dynamic Programming solution for Rod Cutting problem package main import ( "fmt" "math" ) const min float64 = -1 << 63 func rodCut(price []float64, n int) float64 { val := []float64{0} val = append(val, price...) for i := 1; i < n+1; i++ { var max_val = min for j := 0; j < i; j++ { max_val = math.Max(max_val, price[j] + val[i-j-1]) } val[i] = max_val } return val[n] } // Driver program to test rodCut function func main() { arr := []float64{1, 5, 8, 9, 10, 17, 17, 20} var size = len(arr) fmt.Println("Maximum Obtainable Value is",rodCut(arr, size)) }
code/dynamic_programming/src/rod_cutting/rod_cutting.hs
import Data.Array rodCutting :: Int -> [Int] -> Int -- Part of Cosmos by OpenGenus Foundation -- NOTE: great article on lazy DP http://jelv.is/blog/Lazy-Dynamic-Programming/ rodCutting x priceList | x < 0 = 0 | otherwise = r!x where priceArray = listArray (0, length priceList) priceList -- for faster indexing into prices r = listArray (0,x) (0: map f [1..x]) f k = maximum [priceArray!(i-1) + rodCutting (k-i) priceList | i <- [1..k]]
code/dynamic_programming/src/rod_cutting/rod_cutting.py
# Part of Cosmos by OpenGenus Foundation # Code contributed by Debajyoti Halder # A Dynamic Programming solution for Rod cutting problem INT_MIN = -32767 def cutRod(price, n): val = [0 for x in range(n + 1)] val[0] = 0 for i in range(1, n + 1): max_val = INT_MIN for j in range(i): max_val = max(max_val, price[j] + val[i - j - 1]) val[i] = max_val return val[n] # Driver program to test above functions arr = [1, 5, 8, 9, 10, 17, 17, 20] size = len(arr) print("Maximum Obtainable Value is " + str(cutRod(arr, size)))
code/dynamic_programming/src/shortest_common_supersequence/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter Collaborative effort by [OpenGenus](https://github.com/opengenus)
code/dynamic_programming/src/shortest_common_supersequence/scs.java
/* Part of Cosmos by OpenGenus Foundation */ import java.util.*; import java.lang.*; import java.io.*; /* A DP based program to find length of the shortest supersequence */ public class SCS { // Returns length of the shortest supersequence of X and Y static int superSequence(String X, String Y, int m, int n) { int dp[][] = new int[m+1][n+1]; for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0) dp[i][j] = j; else if (j == 0) dp[i][j] = i; else if (X.charAt(i-1) == Y.charAt(j-1)) dp[i][j] = 1 + dp[i-1][j-1]; //Since we need to minimize the length else dp[i][j] = 1 + Math.min(dp[i-1][j], dp[i][j-1]); } } return dp[m][n]; } //Main function public static void main(String args[]) { String X = "ABCBDAB"; String Y = "BDCABA"; System.out.println("Length of the shortest supersequence is "+ superSequence(X, Y, X.length(),Y.length())); } }
code/dynamic_programming/src/shortest_common_supersequence/shortest_common_supersequence.cpp
/* Part of Cosmos by OpenGenus Foundation */ #include <iostream> #include <cstring> using namespace std; const int MAX = 1010; int memo[MAX][MAX]; // used for memoization // Function to find length of shortest common supersequence // between sequences X[0..m-1] and Y[0..n-1] int SCSLength(string& X, string& Y, int m, int n) { // if we have reached the end of either sequence, return // length of other sequence if (m == 0 || n == 0) return n + m; // if we have already computed this state if (memo[m - 1][n - 1] > -1) return memo[m - 1][n - 1]; // if last character of X and Y matches if (X[m - 1] == Y[n - 1]) return memo[m - 1][n - 1] = SCSLength(X, Y, m - 1, n - 1) + 1; else // else if last character of X and Y don't match return memo[m - 1][n - 1] = 1 + min(SCSLength(X, Y, m, n - 1), SCSLength(X, Y, m - 1, n)); } // helper function int findSCSLength(string& X, string& Y) { memset(memo, -1, sizeof memo); return SCSLength(X, Y, X.length(), Y.length()); } // main function int main() { string X = "ABCBDAB", Y = "BDCABA"; cout << "The length of shortest common supersequence is " << findSCSLength(X, Y) << '\n'; return 0; }
code/dynamic_programming/src/shortest_common_supersequence/shortest_common_supersequence.py
# Part of Cosmos by OpenGenus Foundation # shortest common supersequence using dp def min(a, b): if a > b: return b else: return a def superSeq(X, Y, m, n): dp = [] for i in range(m + 1): l2 = [] for j in range(n + 1): if not (i): l2.append(j) elif not (j): l2.append(i) elif X[i - 1] == Y[j - 1]: l2.append(1 + dp[i - 1][j - 1]) else: l2.append(1 + min(dp[i - 1][j], l2[j - 1])) dp.append(l2) return dp[m][n] X = "FABCDF" Y = "HBABCDEF" # longest supersequence can be HBFABCDEF print("Length of the shortest supersequence = ", superSeq(X, Y, len(X), len(Y)))
code/dynamic_programming/src/subset_sum/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter Collaborative effort by [OpenGenus](https://github.com/opengenus)
code/dynamic_programming/src/subset_sum/subset_sum.cpp
/* Part of Cosmos by OpenGenus Foundation */ #ifndef SUBSET_SUM #define SUBSET_SUM #include <iterator> /* * Check whether is possible to * get value sum from a subset * of the [begin:end) */ // complexity: time: O(sum * n), space: O(sum) template<typename _BidirectionalIter, typename _ValueType = typename std::iterator_traits<_BidirectionalIter>::value_type> bool isSubsetSum(_BidirectionalIter begin, _BidirectionalIter end, _ValueType sum) { auto sz = std::distance(begin, end); bool subset[2][sum + 1]; for (int i = 0; i <= sz; i++) { auto x = begin; std::advance(x, i - 1); for (int j = 0; j <= sum; j++) { // A subset with sum 0 is always possible if (j == 0) subset[i % 2][j] = true; // If there exists no element // no sum is possible else if (i == 0) subset[i % 2][j] = false; else if (*x <= j) subset[i % 2][j] = subset[(i + 1) % 2][j - *x] || subset[(i + 1) % 2][j]; else subset[i % 2][j] = subset[(i + 1) % 2][j]; } } return subset[sz % 2][sum]; } /* * // complexity: time: O(sum * n), space: O(sum * n) * template<typename _BidirectionalIter, * typename _ValueType = typename std::iterator_traits<_BidirectionalIter>::value_type> * bool * isSubsetSum(_BidirectionalIter begin, _BidirectionalIter end, _ValueType sum) * { * auto sz = std::distance(begin, end); * bool subset[sum + 1][sz + 1]; * * for (int i = 0; i <= sz; ++i) * subset[0][i] = true; * * for (int i = 1; i <= sum; ++i) * subset[i][0] = false; * * for (int i = 1; i <= sum; ++i) * for (int j = 1; j <= sz; ++j) * { * auto x = begin; * std::advance(x, j - 1); * * subset[i][j] = subset[i][j - 1]; * if (i >= *x) * subset[i][j] = subset[i][j] || subset[i - *x][j - 1]; * } * * return subset[sum][sz]; * } */ #endif // SUBSET_SUM
code/dynamic_programming/src/subset_sum/subset_sum.go
/* Part of Cosmos by OpenGenus Foundation */ package main import "fmt" const TargetSize int = 200 /* Expected Output: Current subset is [1 4 8 9 34 23 17 32] We can't get sum 113 from set We can get sum 9 from set We can't get sum 15 from set We can't get sum 20 from set We can get sum 31 from set */ func subSetSum(subset []int, dp [][]int) { for i := range dp { dp[i] = make([]int, TargetSize+1) for j := range dp[i] { dp[i][j] = 0 } //If sum is 0, then it's true dp[i][0] = 1 } for i := 1; i <= len(subset); i++ { for j := 0; j < TargetSize; j++ { dp[i][j] = dp[i-1][j] if j >= subset[i-1] { dp[i][j] += dp[i-1][j-subset[i-1]] } } } } func main() { input := []int{1, 4, 8, 9, 34, 23, 17, 32} // The value of dp[i][j] will be true if there is a // dp of set[0..i-1] with sum equal to j dp := make([][]int, len(input)+1) subSetSum(input, dp) sum := []int{113, 9, 15, 20, 31} fmt.Printf("Current subset is %v\n", input) for _, v := range sum { if dp[len(input)][v] == 0 { fmt.Printf("We can't get sum %d from set\n", v) } else { fmt.Printf("We can get sum %d from set\n", v) } } }
code/dynamic_programming/src/subset_sum/subset_sum.java
/* Part of Cosmos by OpenGenus Foundation */ // A Java programm for subset sum problem using Dynamic Programming. class subset_sum { static boolean isSubsetSum(int set[], int n, int sum) { boolean subset[][] = new boolean[sum+1][n+1]; for (int i = 0; i <= n; i++) subset[0][i] = true; for (int i = 1; i <= sum; i++) subset[i][0] = false; for (int i = 1; i <= sum; i++) { for (int j = 1; j <= n; j++) { subset[i][j] = subset[i][j-1]; if (i >= set[j-1]) subset[i][j] = subset[i][j]||subset[i - set[j-1]][j-1]; } } return subset[sum][n]; } public static void main (String args[]) { int set[] = {3, 34, 4, 12, 5, 7}; int sum = 19; int n = set.length; if (isSubsetSum(set, n, sum) == true) System.out.println("Subset found"); else System.out.println("No subset found"); } }
code/dynamic_programming/src/subset_sum/subset_sum.py
# Part of Cosmos by OpenGenus Foundation def can_get_sum(items, target): dp = (target + 1) * [False] reachable = (target + 1) * [0] reachable[0] = 0 dp[0] = True reachable[1] = 1 i = 0 q = 1 while i < len(items) and not dp[target]: aux = q for j in range(0, aux): x = reachable[j] + items[i] if x <= target and not dp[x]: reachable[q] = x q += 1 dp[x] = True i += 1 return dp[target] print(can_get_sum([1, 2, 3], 6)) print(can_get_sum([1, 2, 3], 7))
code/dynamic_programming/src/tiling_problem/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter Collaborative effort by [OpenGenus](https://github.com/opengenus)
code/dynamic_programming/src/tiling_problem/tiling_problem.c
#include <stdio.h> long long int tiling(int n) { long long int tile[n + 1]; int i; tile[0] = 1; tile[1] = 1; tile[2] = 2; for (i = 3; i <= n; i++) tile[i] = tile[i - 1] + tile[i - 2]; return (tile[n]); } int main() { int n; printf("Enter Number of tiles: "); scanf("%d", &n); printf("Number of ways to arrange tiles is %lli \n", tiling(n)); return (0); }
code/dynamic_programming/src/tiling_problem/tiling_problem.cpp
#include <iostream> #include <vector> using namespace std; // Part of Cosmos by OpenGenus Foundation long long tiling(int n) { vector<long long int> tile(n + 1); tile[0] = 1; tile[1] = 1; tile[2] = 2; for (int i = 3; i <= n; i++) tile[i] = tile[i - 1] + tile[i - 2]; return tile[n]; } int main() { int n; cout << "enter the value of n\n"; cin >> n; cout << "total ways to arrange the tiles is " << tiling(n); }
code/dynamic_programming/src/tiling_problem/tiling_problem.py
def tiling(n): tile = [0 for i in range(n + 1)] tile[0] = 1 tile[1] = 1 tile[2] = 2 for i in range(3, n + 1): tile[i] = tile[i - 1] + tile[n - 2] return tile[n] if __name__ == "__main__": n = 10 print(tiling(n))
code/dynamic_programming/src/trapping_rain_water/rainwater_trapping.cpp
#include<iostream> using namespace std; int main() { int n; cin>>n; int arr[n]; for(int i=0;i<n;i++){ cin>>arr[i]; } int left_highest[n]; int right_highest[n]; int l_high=arr[0]; int i=0; int r_high=arr[n-1]; for(i=0;i<n;i++){ if(arr[i]>=l_high){ left_highest[i]=arr[i]; l_high=arr[i]; } else left_highest[i]=l_high; } for(i=n-1;i>=0;i--){ if(arr[i]>=r_high){ right_highest[i]=arr[i]; r_high=arr[i]; } else right_highest[i]=r_high; } int water_saved=0; for(i=0;i<n;i++){ water_saved+=min(left_highest[i],right_highest[i])-arr[i]; } cout<<water_saved; return 0; }
code/dynamic_programming/src/trapping_rain_water/trapping_rain_water.cpp
/* Problem Description - https://leetcode.com/problems/trapping-rain-water/description/ Test Cases - Input: [0,1,0,2,1,0,1,3,2,1,2,1] Output: 6 */ #include<iostream> #include<vector> using namespace std; int trapRainWater(int *arr, int n) { if(n < 3) return 0; vector<pair<int,int>>indexes; for(int i = 0 ; i < n ; i++) { bool check = false; int j = i + 1; int maxVal = 0; int index = i + 1; for(; j < n ; j++) // finding the corresponding value for the given start index { if(maxVal <= arr[j]) { maxVal = arr[j]; index = j; if(maxVal >= arr[i]) // if current value exceeds or is equal to arr[i] break break; } } if(index != i + 1) { pair<int,int>e; e.first = i; e.second = index; // insert it as a pair to show (start, end) for our water segment indexes.push_back(e); i = index - 1; } } int totalVol = 0; for(int i = 0 ; i < indexes.size() ; i++) { pair<int,int>p = indexes[i]; int minHeight = min(arr[p.first], arr[p.second]); // choose the minimum of the two boundaries to get max height of water enclosed // compute water stored corresponding to each cell inside a segment for(int j = p.first + 1 ; j < p.second ; j++) totalVol += abs(minHeight - arr[j]); } return totalVol; } int main() { int n; cin>>n; int arr[n]; for(int i = 0 ; i < n ; i++) cin>>arr[i]; cout<<trapRainWater(arr, n)<<endl; }
code/dynamic_programming/src/trapping_rain_water/trapping_rain_water.java
public class Main { public static void main(String args[]) { int[] heightArray = {1, 2, 1, 3, 1, 2, 1, 4, 1, 0, 0, 2, 1, 4}; System.out.println(trap_rain_water(heightArray)); } public static int trap_rain_water(int[] height) { int result = 0; if(height==null) { return result; } int left[] = new int[height.length]; int right[] = new int[height.length]; //left[i] will contain height of tallest bar on the left side of i'th bar left[0] = height[0]; for(int i=1; i<height.length; i++) { left[i] = Math.max(left[i-1], height[i]); } //right[i] will contain height of tallest bar on the right side of i'th bar right[height.length - 1] = height[height.length - 1]; for(int i=height.length-2; i>=0; i--) { right[i] = Math.max(right[i+1], height[i]); } //amount of water collected on i'th bar will be min(left[i], right[i]) - height[i] for(int i=0; i<height.length; i++) { result+= Math.min(left[i], right[i]) - height[i]; } return result; } }
code/dynamic_programming/src/trapping_rain_water/trapping_rain_water.py
# Python3 implementation of the approach # Function to return the maximum # water that can be stored def maxWater(arr, n) : # To store the maximum water # that can be stored res = 0; # For every element of the array for i in range(1, n - 1) : # Find the maximum element on its left left = arr[i]; for j in range(i) : left = max(left, arr[j]); # Find the maximum element on its right right = arr[i]; for j in range(i + 1 , n) : right = max(right, arr[j]); # Update the maximum water res = res + (min(left, right) - arr[i]); return res; # Driver code if __name__ == "__main__" : arr = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]; n = len(arr); print(maxWater(arr, n));
code/dynamic_programming/src/unique_paths/unique_paths.cpp
// Part of Cosmos by OpenGenus Foundation #include<bits/stdc++.h> using namespace std; //Tabulation method // Time complexity: O(m*n) int uniquePaths(int m, int n) { int dp[m][n]; for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ if(i==0 || j==0) dp[i][j]=1; else dp[i][j]=dp[i-1][j]+dp[i][j-1]; } } return dp[m-1][n-1]; } //nCr method // Time complexity: O(m+n) int uniquePaths1(int m, int n) { int N=m+n-2; int r=m-1; double res=1; for(int i=1;i<=r;i++){ res=res*(N-r+i)/i; } return (int)res; } // Brute force recursive method // Time complexity: O(2^(m+n)) int uniquePaths2(int m, int n) { if(m==1 || n==1) return 1; return uniquePaths2(m-1,n)+uniquePaths2(m,n-1); } //Time complexity: O(m*n) int solve(int i, int j, vector<vector<int>> &dp, int &m, int &n){ if (i == m - 1 || j == n - 1) return 1; if (dp[i][j] != 0) return dp[i][j]; dp[i][j] = solve(i + 1, j, dp, m, n) + solve(i, j + 1, dp, m, n); return dp[i][j]; } int uniquePaths3(int m, int n){ vector<vector<int>> dp(m, vector<int>(n, 0)); return solve(0, 0, dp, m, n); } int main(){ int m,n; cin>>m>>n; cout<<uniquePaths(m,n)<< endl; cout<<uniquePaths1(m,n) << endl; cout<<uniquePaths2(m,n) << endl; cout<<uniquePaths3(m,n) << endl; return 0; }
code/dynamic_programming/src/weighted_job_scheduling/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter Collaborative effort by [OpenGenus](https://github.com/opengenus)
code/dynamic_programming/src/weighted_job_scheduling/weighted_job_scheduling.cpp
/* * Part of Cosmos by OpenGenus Foundation * C++ program for weighted job scheduling using Dynamic Programming and Binary Search */ #include <vector> #include <iostream> #include <algorithm> using namespace std; // A job has start time, finish time and profit. //index is used to store its given position as we will going to do sorting struct Job { int start, finish, profit, index; }; // A utility function that is used for sorting events // according to finish time bool jobComparator(Job s1, Job s2) { return s1.finish < s2.finish; } // A Binary Search based function to find the latest job // (before current job) that doesn't conflict with current // job. "index" is index of the current job. This function // returns -1 if all jobs before index conflict with it. The // array jobs[] is sorted in increasing order of finish time int latestNonConflict(const vector<Job> &jobs, int index) { // Initialize 'lo' and 'hi' for Binary Search int lo = 0, hi = index - 1; // Perform binary Search iteratively while (lo <= hi) { int mid = (lo + hi) / 2; if (jobs[mid].finish <= jobs[index].start) { if (jobs[mid + 1].finish <= jobs[index].start) lo = mid + 1; else return mid; } else hi = mid - 1; } return -11; //-11 just a flag value but kept as same to that given to index 0 see: MaxProfit func //so that backtracking can be done } // The main function that finds the subset of jobs // associated with maximum profit such that no two // jobs in the subset overlap. void MaxProfit(vector<Job> &arr) { int n = arr.size(); // Sort jobs according to finish time sort(arr.begin(), arr.end(), jobComparator); //reason for using index // Create an array to store solutions of subproblems. // DP[i] stores the Jobs involved and their total profit // till arr[i] (including arr[i]) vector<int> DP(n + 2); // initialize DP[0] to arr[0] DP[0] = arr[0].profit; //contain what is the latest non conflicting job with the current job vector<int> nConflict; //no job non-conflicting with one job nConflict.push_back(-11); //-11 is just a flag value for (int i = 1; i < n; i++) nConflict.push_back(latestNonConflict(arr, i)); // Fill entries in DP[] using recursive property //recurrence for (int i = 1; i < n; i++) { int val = nConflict[i]; DP[i] = max(DP[i - 1], DP[val] + arr[i].profit); } //finding jobs included in max profit int i = n - 1; cout << "Optimal jobs are - "; while (true) { //terminating condition if (i < 0) //basically checking case of if it is equal to index of any job --(-11) break; //DP[i] will be one of the two values from which it is derived(shown above) if (i == 0) { cout << arr[i].index + 1; break; } else if (DP[i] == DP[i - 1]) i--; else { cout << arr[i].index + 1 << " "; i = nConflict[i]; } } cout << "\nMaximum Profit = " << DP[n - 1] << "\n"; } int main() { //example test case vector<Job> arr(4); arr[0] = {3, 5, 20, 0}; arr[1] = {1, 2, 50, 1}; arr[2] = {6, 19, 100, 2}; arr[3] = {2, 100, 200, 3}; MaxProfit(arr); return 0; }
code/dynamic_programming/src/weighted_job_scheduling/weighted_job_scheduling.py
# Python3 program for weighted job scheduling using # Naive Recursive Method # Importing the following module to sort array # based on our custom comparison function from functools import cmp_to_key # A job has start time, finish time and profit class Job: def __init__(self, start, finish, profit): self.start = start self.finish = finish self.profit = profit # A utility function that is used for # sorting events according to finish time def jobComparataor(s1, s2): return s1.finish < s2.finish # Find the latest job (in sorted array) that # doesn't conflict with the job[i]. If there # is no compatible job, then it returns -1 def latestNonConflict(arr, i): for j in range(i - 1, -1, -1): if arr[j].finish <= arr[i - 1].start: return j return -1 # A recursive function that returns the # maximum possible profit from given # array of jobs. The array of jobs must # be sorted according to finish time def findMaxProfitRec(arr, n): # Base case if n == 1: return arr[n - 1].profit # Find profit when current job is included inclProf = arr[n - 1].profit i = latestNonConflict(arr, n) if i != -1: inclProf += findMaxProfitRec(arr, i + 1) # Find profit when current job is excluded exclProf = findMaxProfitRec(arr, n - 1) return max(inclProf, exclProf) # The main function that returns the maximum # possible profit from given array of jobs def findMaxProfit(arr, n): # Sort jobs according to finish time arr = sorted(arr, key = cmp_to_key(jobComparataor)) return findMaxProfitRec(arr, n) # Driver code values = [ (3, 10, 20), (1, 2, 50), (6, 19, 100), (2, 100, 200) ] arr = [] for i in values: arr.append(Job(i[0], i[1], i[2])) n = len(arr) print("The optimal profit is", findMaxProfit(arr, n)) # This code is code contributed by Kevin Joshi
code/dynamic_programming/src/wildcard_matching/wildcard.cpp
//Part of Cosmos by OpenGenus Foundation bool isMatch(string s, string p) { /* s is the string p is the pattern containing '?' and '*' apart from normal characters. */ int m=s.length(), n=p.length(); bool dp[m+1][n+1]; // Initialise each cell of the dp table with false for(int i=0;i<m+1;i++) for(int j=0;j<n+1;j++) dp[i][j]=false; for(int i=0;i<m+1;i++) { for(int j=0;j<n+1;j++) { // When both string s and pattern p is empty. if (i==0 && j==0) dp[i][j]=true; // When s is empty else if (i == 0) { dp[i][j]=(p[j-1]=='*' && dp[i][j-1]); } // When the pattern is empty else if (j == 0) dp[i][j]=false; // When the characters p[j-1] matches character s[i-1] or when // p[j-1] is a '?'. Both will consume 1 character of s. else if (p[j-1] == s[i-1] || p[j-1] == '?') dp[i][j]=dp[i-1][j-1]; // p[j-1]='*' // A '*' can consume 0 or multiple characters. else if (p[j-1]=='*') dp[i][j]=dp[i-1][j] || dp[i][j-1]; // If p[j-1] is any character other than those above. else dp[i][j]=false; } } return dp[m][n]; }
code/dynamic_programming/src/wildcard_matching/wildcard.md
# Wildcard Matching Learn more: [Wildcard Pattern Matching (Dynamic Programming)](https://iq.opengenus.org/wildcard-pattern-matching-dp/) ## Description You have a string `s` of length `m` and a pattern `p` of length `n`. With wildcard matching enabled ie. character `?` in `p` can replace 1 character of `s` and a `*` in `p` can replace any number of characters of `s` including 0 character, find if `s` is equivalent to `p`. Return **true** if `s` is equivalent to `p` else **false**. ## Thought Process Let's follow 1-based indexing and denote s[i,j] as the substring of s from ith to jth character including both. Same for p. So for example, if s is "abcde", then s[2,4] is the substring "bcd". <details> <summary>What's the problem in terms of s, p, m, and n?</summary> </br> Return true when s[1:m] is equivalent to p[1:n]. </details> <details> <summary>What's the Subproblem in terms of s and p?</summary> </br> <ol> <li>For an index i and an index j, we want to find if s[1:i] is equivalent to p[1:j].</li> <li>Note that a subproblem can be formulated from the end of strings as well but then you'll need to fill the DP table from bottom to top.</li> </ol> </details> <details> <summary>Solution</summary> </br> <ol> <li>We iterate over all i from 1 to m. For each i, we iterate over all j from 1 to n. At each point, we check if s[1:i] is equivalent to p[1:j] and fill true or false in the cell dp[i][j] of the dp table. Recording this will help in finding answers to further i and j which we'll see in the recurrence relation.</li> <li>The final answer is dp[m][n].</li> </ol> </details> <details> <summary>What's the recurrence relation?</summary> </br> <ol> <li>If the jth character of p is the same as ith character of s, then s[1:i]=p[1:j] if s[1:i-1]=p[1:j-1] ie. dp[i][j]=dp[i-1][j-1]. Also, when jth character of p is ?, it will consume the ith character of s. Hence same for it.</li> <li>If the jth character of p is '*', then it can consume 0 characters ie. s[1:i]=p[1:j-1] or several characters ie. dp[i][j]=dp[i][j-1] || dp[i-1][j].</li> </ol> </details> <details> <summary>What's the time complexity?</summary> </br> Since we need to lookup atmost two adjacent cells to fill any cell in the dp table, filling a cell is an O(1) process. And we need to fill m*n such cells. Thus the complexity is O(mn). </details> <details> <summary>What's next?</summary> </br> <ol> <li>Think about the subproblem that each cell of the DP table handles and come up with the edge cases.</li> <li>What changes when you consider 0-based indexing for strings? </li> </ol> </details>
code/dynamic_programming/test/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter
code/dynamic_programming/test/longest_repeating_subsequence/longest_repeating_subsequence_test.cpp
/* Part of Cosmos by OpenGenus Foundation */ #include <iostream> #include <string> #include <cassert> #include "../../src/longest_repeating_subsequence/longest_repeating_subsequence.cpp" int main() { using namespace std; std::string s1 = "aab"; assert(longestRepeatingSubsequence(s1) == 1); }
code/dynamic_programming/test/subset_sum/test_subset_sum.cpp
/* Part of Cosmos by OpenGenus Foundation */ #ifndef SUBSET_SUM_TEST #define SUBSET_SUM_TEST #include <iostream> #include <list> #include <cassert> #include "../../src/subset_sum/subset_sum.cpp" int main() { using namespace std; int vz[0]; int v[] = {1, 2, 15, 8, 5}; list<int> l{1, 2, 15, 8, 5}; assert(isSubsetSum(vz, vz, 0)); assert(isSubsetSum(v, v + sizeof(v) / sizeof(v[0]), 13)); assert(isSubsetSum(l.begin(), l.end(), 13)); assert(isSubsetSum(vz, vz, 13) == false); assert(isSubsetSum(v, v + sizeof(v) / sizeof(v[0]), 4) == false); assert(isSubsetSum(l.begin(), l.end(), 4) == false); return 0; } #endif // SUBSET_SUM_TEST
code/filters/src/gaussian_filter/gaussian_filter.py
##Author - Sagar Vakkala (@codezoned) from PIL import Image import numpy def main(): ##Load the Image (Change source.jpg with your image) image = Image.open("source.jpg") ##Get the width and height width, height = image.size ##Initialise a null matrix pix = numpy.zeros(shape=(width, height, 3), dtype=numpy.uint8) ##Same again matris = numpy.zeros(shape=(width, height, 3), dtype=numpy.uint8) # Neighbor matrice to be filtered pixel neighbour_matrice = numpy.zeros(shape=(5, 5)) for i in range(width): for j in range(height): # Get and assign image's RGB values rgb_im = image.convert("RGB") r, g, b = rgb_im.getpixel((i, j)) pix[i][j] = r, g, b if i >= 2 & i < (width - 2) & j >= 2 & j < (height - 2): for m in range(3): toplam = 0.0 for k in range(5): for l in range(5): neighbour_matrice[k][l] = matris[k + i - 2][l + j - 2][ m ] # Create neighbor matrice's indexs(exclude a frame size=2) for k in range(5): for l in range(5): toplam = toplam + ( neighbour_matrice[k][l] * 0.04 ) # 0.04 is filter value. matris[j][i][m] = int(toplam) # Create an image with RGB values img = Image.fromarray(matris, "RGB") ##Save and show the image img.save("target.jpg") img.show() if __name__ == "__main__": main()
code/filters/src/median_filter/median_filter.py
##Author - Sagar Vakkala (@codezoned) import numpy from PIL import Image def median_filter(data, filter_size): temp_arr = [] index = filter_size // 2 data_final = [] data_final = numpy.zeros((len(data), len(data[0]))) for i in range(len(data)): # Iterate over the Image Array for j in range(len(data[0])): for z in range(filter_size): if i + z - index < 0 or i + z - index > len(data) - 1: for c in range(filter_size): temp_arr.append(0) else: if j + z - index < 0 or j + index > len(data[0]) - 1: temp_arr.append(0) else: for k in range(filter_size): temp_arr.append(data[i + z - index][j + k - index]) temp_arr.sort() data_final[i][j] = temp_arr[len(temp_arr) // 2] temp_arr = [] return data_final def main(): ##Replace someImage with the noise image img = Image.open("someImage.png").convert("L") arr = numpy.array(img) ##3 defines the no of layers for the filter ##It also defines that the filter will be 3x3 size. Change 3 to 5 for a 5x5 filter removed_noise = median_filter(arr, 3) img = Image.fromarray(removed_noise) img.show() if __name__ == "__main__": main()
code/game_theory/src/expectimax/expectimax.py
""" Expectimax game playing algorithm Alex Day Part of Cosmos by OpenGenus Foundation """ from abc import ABC, abstractmethod import math from random import choice class Board(ABC): @abstractmethod def terminal(): """ Determine if the current state is terminal Returns ------- bool: If the board is terminal """ return NotImplementedError() @abstractmethod def get_child_board(player): """ Get all possible next moves for a given player Parameters ---------- player: int the player that needs to take an action (place a disc in the game) Returns ------- List: List of all possible next board states """ return NotImplementedError() def expectimax(player: int, board, depth_limit, evaluate): """ expectimax algorithm with limited search depth. Parameters ---------- player: int the player that needs to take an action (place a disc in the game) board: the current game board instance. Should be a class that extends Board depth_limit: int the tree depth that the search algorithm needs to go further before stopping evaluate: fn[Board, int] Some function that evaluates the board at the current position Returns ------- placement: int or None the column in which a disc should be placed for the specific player (counted from the most left as 0) None to give up the game """ max_player = player next_player = board.PLAYER2 if player == board.PLAYER1 else board.PLAYER1 def value(board, depth_limit): """ Evaluate the board at the current state Args: board (Board): Current board state depth_limit (int): Depth limit Returns: float: Value of the board """ return evaluate(player, board) def max_value(board, depth_limit: int) -> float: """ Calculate the maximum value for play if players acts optimally Args: player (int): Player token to maximize value of board (Board): Current board state depth_limit (int): Depth limit Returns: float: Maximum value possible if players play optimally """ # Check if terminal or depth limit has been reached if depth_limit == 0 or board.terminal(): # If leaf node return the calculated board value return value(board, depth_limit) # If not leaf then continue searching for maximum value best_value = -math.inf # Generate all possible moves for maximizing player and store the # max possible value while exploring down to terminal nodes for move, child_board in board.get_child_boards(player): best_value = max(best_value, min_value(child_board, depth_limit - 1)) return best_value def min_value(board, depth_limit: int) -> float: """ Calculate a uniformly random move for the minplayer Args: player (int): Player token to minimize value of board (Board): Current board state depth_limit (int): Depth limit Returns: float: Minimum value possible if players play optimally """ # Check if terminal or depth limit has been reached if depth_limit == 0 or board.terminal(): # If leaf node return the calculated board value return value(board, depth_limit) # If not leaf then continue searching for minimum value # Generate all possible moves for minimizing player and store the # min possible value while exploring down to terminal nodes move, child_board = choice(board.get_child_boards(ext_player)) return max_value(child_board, depth_limit - 1) return best_value # Start off with the best score as low as possible. We want to maximize # this for our turn best_score = -math.inf placement = None # Generate all possible moves and boards for the current player for pot_move, pot_board in board.get_child_boards(player): # Calculate the minimum score for the player at this board pot_score = min_value(pot_board, depth_limit - 1) # If this is greater than the best_score then update if pot_score > best_score: best_score = pot_score placement = pot_move return placement