filename stringlengths 7 140 | content stringlengths 0 76.7M |
|---|---|
code/dynamic_programming/src/binomial_coefficient/binomial_coefficient.c | /*
* dynamic programming | binomial coefficient | C
* Part of Cosmos by OpenGenus Foundation
* A DP based solution that uses table C[][] to calculate the Binomial Coefficient
*/
#include <stdio.h>
// A utility function to return minimum of two integers
int
min(int a, int b)
{
return (a < b ? a : b);
}
// R... |
code/dynamic_programming/src/binomial_coefficient/binomial_coefficient.cpp | // dynamic programming | binomial coefficient | C++
// Part of Cosmos by OpenGenus Foundation
#include <iostream>
#include <vector>
using namespace std;
/*
* Computes C(n,k) via dynamic programming
* C(n,k) = C(n-1, k-1) + C(n-1, k)
* Time complexity: O(n*k)
* Space complexity: O(k)
*/
long long binomialCoe... |
code/dynamic_programming/src/binomial_coefficient/binomial_coefficient.ex | defmodule BinomialCoefficient do
def binn_coef(n, k) do
cond do
n <= 0 or k <= 0 ->
{:error, :non_positive}
n < k ->
{:error, :k_greater}
true ->
p = n - k
{rem_fact_n, div_fact} =
if p > k do
{
n..(p + 1)
|> En... |
code/dynamic_programming/src/binomial_coefficient/binomial_coefficient.java | // dynamic programming | binomial coefficient | Java
// Part of Cosmos by OpenGenus Foundation
import java.io.*;
import java.lang.*;
import java.math.*;
import java.util.*;
class BinomialCoefficient{
static int binomialCoeff(int n, int k) {
if (k>n) {
return 0;
}
int c[] = new int[k+1];
int i, j;
... |
code/dynamic_programming/src/binomial_coefficient/binomial_coefficient.js | // dynamic programming | binomial coefficient | javascript js
// Part of Cosmos by OpenGenus Foundation
/*Call the function with desired values of n and k.
'ar' is the array name.*/
function binomialCoefficient(n, k) {
if (k > n) {
console.log("Not possible.");
return;
}
const ar = [n + 1];
for (let ... |
code/dynamic_programming/src/binomial_coefficient/binomial_coefficient.py | # dynamic programming | binomial coefficient | Python
# Part of Cosmos by OpenGenus Foundation
import numpy as np
# implementation using dynamic programming
def binomialCoefficient(n, k, C=None):
if k < 0 or n < 0:
raise ValueError("n,k must not be less than 0")
if k > n:
return 0
k = min... |
code/dynamic_programming/src/bitmask_dp/README.md | # Bitmask DP
Bitmask DP is commonly used when we have smaller constraints and it's easier to try out all the possibilities to arrive at the solution.
Please feel free to add more explaination and problems for this topic! |
code/dynamic_programming/src/bitmask_dp/bitmask_dp_prob#1.cpp | /* Part of Cosmos by OpenGenus Foundation */
/* Problem Statement:
There are k types ties, uniquely identified by id from 1 to k. n ppl are
invited to a party. Each of them have a collection of ties. To look unique,
they decide that none of them will wear same type of tie. Count the number
of ways th... |
code/dynamic_programming/src/boolean_parenthesization/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/boolean_parenthesization/boolean_parenthesization.c | /*
* dynamic programming | boolean parenthesization | C
* Part of Cosmos by OpenGenus Foundation
*/
#include <stdio.h>
// Dynamic programming implementation of the boolean
// parenthesization problem using 'T' and 'F' as characters
// and '&', '|' and '^' as the operators
int
boolean_parenthesization(char c[], ch... |
code/dynamic_programming/src/boolean_parenthesization/boolean_parenthesization.cpp | // dynamic programming | boolean parenthesization | C++
// Part of Cosmos by OpenGenus Foundation
#include <iostream>
#include <cstring>
// Dynamic programming implementation of the boolean
// parenthesization problem using 'T' and 'F' as characters
// and '&', '|' and '^' as the operators
int boolean_parenthesizatio... |
code/dynamic_programming/src/boolean_parenthesization/boolean_parenthesization.java | // dynamic programming | boolean parenthesization | Java
// Part of Cosmos by OpenGenus Foundation
/*** Dynamic programming implementation of the boolean
* parenthesization problem using 'T' and 'F' as characters
* and '&', '|' and '^' as the operators
***/
class boolean_parenthesization{
public static int boo... |
code/dynamic_programming/src/boolean_parenthesization/boolean_parenthesization.py | # dynamic programming | boolean parenthesization | Python
# Part of Cosmos by OpenGenus Foundation
# Dynamic programming implementation of the boolean
# parenthesization problem using 'T' and 'F' as characters
# and '&', '|' and '^' as the operators
def boolean_parenthesization(c, o, n):
t = [[0 for i in range(n... |
code/dynamic_programming/src/boolean_parenthesization/boolean_parenthesization.swift | // dynamic programming | boolean parenthesization | Swift
// Part of Cosmos by OpenGenus Foundation
// Dynamic programming implementation of the boolean
// parenthesization problem using 'T' and 'F' as characters
// and '&', '|' and '^' as the operators
class BooleanParenthesization {
private var characters = [Ch... |
code/dynamic_programming/src/box_stacking/README.md | # Box Stacking
## Description
Given a set of n types of 3D rectangular boxes, find the maximum height
that can be reached stacking instances of these boxes. Some onservations:
- A box can be stacked on top of another box only if the dimensions of the
2D base of the lower box are each strictly larger than those of th... |
code/dynamic_programming/src/box_stacking/box_stacking.cpp | // dynamic programming | box stacking | C++
// Part of Cosmos by OpenGenus Foundation
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
// Struct to represent the boxes
struct Box
{
int height, width, length;
// Initializer
Box()
{
}
Box(int h, int w, int l) : ... |
code/dynamic_programming/src/box_stacking/box_stacking.java | // dynamic programming | box stacking | Java
// Part of Cosmos by OpenGenus Foundation
import java.util.Arrays;
public class BoxStacking {
public int maxHeight(Dimension[] input) {
//get all rotations of box dimension.
//e.g if dimension is 1,2,3 rotations will be 2,1,3 3,2,1 3,1,2 . Here leng... |
code/dynamic_programming/src/box_stacking/box_stacking.py | """
dynamic programming | box stacking | Python
Part of Cosmos by OpenGenus Foundation
"""
from collections import namedtuple
from itertools import permutations
dimension = namedtuple("Dimension", "height length width")
def create_rotation(given_dimensions):
"""
A rotation is an order wherein length is grea... |
code/dynamic_programming/src/catalan/catalan_number.go | package dynamic
import "fmt"
var errCatalan = fmt.Errorf("can't have a negative n-th catalan number")
// NthCatalan returns the n-th Catalan Number
// Complexity: O(n²)
func NthCatalanNumber(n int) (int64, error) {
if n < 0 {
//doesn't accept negative number
return 0, errCatalan
}
var catalanNumberList []int... |
code/dynamic_programming/src/coin_change/README.md | # Coin Change
## Description
Given a set of coins `S` with values `{ S1, S2, ..., Sm }`,
find the number of ways of making the change to a certain value `N`.
There is an infinite quantity of coins and the order of the coins doesn't matter.
For example:
For `S = {1, 2, 3}` and `N = 4`, the number of possibilities is... |
code/dynamic_programming/src/coin_change/coin_change.java | // dynamic programming | coin change | Java
// Part of Cosmos by OpenGenus Foundation
public class WaysToCoinChange {
public static int dynamic(int[] v, int amount) {
int[][] solution = new int[v.length + 1][amount + 1];
// if amount=0 then just return empty set to make the change
for (int i = 0; i <= v.length... |
code/dynamic_programming/src/coin_change/coin_change.py | #################
## dynamic programming | coin change | Python
## Part of Cosmos by OpenGenus Foundation
#################
def coin_change(coins, amount):
# init the dp table
tab = [0 for i in range(amount + 1)]
tab[0] = 1 # base case
for j in range(len(coins)):
for i in range(1, amount ... |
code/dynamic_programming/src/coin_change/coinchange.c | // dynamic programming | coin change | C
// Part of Cosmos by OpenGenus Foundation
#include<stdio.h>
int
count( int S[], int m, int n )
{
int i, j, x, y;
// We need n+1 rows as the table is consturcted in bottom up manner using
// the base case 0 value case (n = 0)
int table[n + 1][m];
// ... |
code/dynamic_programming/src/coin_change/coinchange.cpp | // dynamic programming | coin change | C++
// Part of Cosmos by OpenGenus Foundation
#include <iostream>
#include <vector>
using namespace std;
int coinWays(int amt, vector<int>& coins) {
// init the dp table
vector<int> dp(amt+1, 0);
int n = coins.size();
dp[0] = 1; // base case
for (int j = 0; j... |
code/dynamic_programming/src/coin_change/coinchange.go | /*
* dynamic programming | coin change | Go
* Part of Cosmos by OpenGenus Foundation
*/
package main
import "fmt"
/*
There are 22 ways to combine 8 from [1 2 3 4 5 6 7 8 9 10]
*/
//DP[i] += DP[i-coint[i]]
//j = coinset,
//i = for each money
func solveCoinChange(coins []int, target int) int {
dp := make([]int, t... |
code/dynamic_programming/src/coin_change/mincoinchange.cpp | // dynamic programming | coin change | C++
// Part of Cosmos by OpenGenus Foundation
// A C++ program to find the minimum number of coins required from the list of given coins to make a given value
// Given a value V, if we want to make change for V cents, and we have infinite supply of each of C = { C1, C2, .. , Cm}
... |
code/dynamic_programming/src/die_simulation/README.md | ## Description
There is a dice simulator which generates random numbers from 0 to 5. You are given an array `constraints` where `constraints[i]` denotes the
maximum number of consecutive times the ith number can be rolled. You are also given `n`, the number of times the dice is to be rolled ie. the number of simulati... |
code/dynamic_programming/src/die_simulation/die_simulation.cpp | // Part of OpenGenus cosmos
#define ll long long
const int mod = 1e9+7;
// Function to add in presence of modulus. We find the modded answer
// as the number of sequences becomes exponential fairly quickly
ll addmod(ll a, ll b)
{
return (a%mod + b%mod) % mod;
}
ll dieSimulator_util(int dex, vector<int>& maxrol... |
code/dynamic_programming/src/digit_dp/DigitDP.java | /* Part of Cosmos by OpenGenus Foundation */
/* How many numbers x are there in the range a to b?
* where the digit d occurs exactly k times in x?
*/
import java.util.Arrays;
public class DigitDP {
private static int d = 3;
private static int k = 5;
private static int[][][] dp = new int[25][25][2];
... |
code/dynamic_programming/src/digit_dp/digit_dp.cpp | /* Part of Cosmos by OpenGenus Foundation
* By: Sibasish Ghosh (https://github.com/sibasish14)
*/
/* How many numbers x are there in the range a to b?
* where the digit d occurs exactly k times in x?
*/
#include <iostream>
#include <vector>
#include <string.h>
using namespace std;
long d = 3;
long k = 5;
long ... |
code/dynamic_programming/src/edit_distance/README.md | # Edit distance
## Description
Edit distance is a way of quantifying how dissimilar two strings (e.g., words) are to one another by counting the minimum number of operations required to transform one string into the other. Edit distances find applications in natural language processing, where automatic spelling corre... |
code/dynamic_programming/src/edit_distance/edit_distance.c | /*
* dynamic programming | edit distance | C
* Part of Cosmos by OpenGenus Foundation
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const int MAX = 1010;
int memo[MAX][MAX]; /* used for memoization */
int
mn(int x, int y)
{
return x < y ? x : y;
}
/* Utility function to find minimum of three... |
code/dynamic_programming/src/edit_distance/edit_distance.cpp | // dynamic programming | edit distance | C++
// Part of Cosmos by OpenGenus Foundation
#include <iostream>
#define MAX 1010
using namespace std;
int memo[MAX][MAX];
/*
* A recursive approach to the edit distance problem.
* Returns the edit distance between a[0...i] and b[0...j]
* Time complexity: O(n*m)
*/
... |
code/dynamic_programming/src/edit_distance/edit_distance.go | /*
* dynamic programming | edit distance | Go
* Part of Cosmos by OpenGenus Foundation
*
* Compile: go build edit_distance.go
*/
package main
import (
"fmt"
"os"
)
func main() {
if len(os.Args) != 3 {
fmt.Println("Wrong input, write input next to the program call")
fmt.Println("Example: ./edit_distance ... |
code/dynamic_programming/src/edit_distance/edit_distance.hs | --- dynamic programming | edit distance | Haskell
--- Part of Cosmos by OpenGenus
--- Adapted from http://jelv.is/blog/Lazy-Dynamic-Programming/
module EditDistance where
import Data.Array
editDistance :: String -> String -> Int
editDistance a b = d m n
where (m, n) = (length a, length b)
a' = listArray (1... |
code/dynamic_programming/src/edit_distance/edit_distance.java | // dynamic programming | edit distance | Java
// Part of Cosmos by OpenGenus Foundation
import java.util.Scanner;
public class edit_distance {
public static int edit_DP(String s,String t){
int l1 = s.length();
int l2 = t.length();
int dp[][] = new int[l1+1][l2+1];
for(int... |
code/dynamic_programming/src/edit_distance/edit_distance.php | <?php
// dynamic programming | edit distance | PHP
// Part of Cosmos by OpenGenus Foundation
function editDistance($str1, $str2)
{
$lenStr1 = strlen($str1);
$lenStr2 = strlen($str2);
if ($lenStr1 == 0) {
return $lenStr2;
}
if ($lenStr2 == 0) {
return $lenStr1;
}
$distance... |
code/dynamic_programming/src/edit_distance/edit_distance.py | # dynamic programming | edit distance | Python
# Part of Cosmos by OpenGenus Foundation
# A top-down DP Python program to find minimum number
# of operations to convert str1 to str2
def editDistance(str1, str2):
def editDistance(str1, str2, m, n, memo):
# If first string is empty, the only option is to
... |
code/dynamic_programming/src/edit_distance/edit_distance.rs | // dynamic programming | edit distance | Rust
// Part of Cosmos by OpenGenus Foundation
use std::cmp;
fn edit_distance(str1: &String, str2: &String) -> usize {
let len_str1 = str1.len();
let len_str2 = str2.len();
if len_str1 == 0 {
return len_str2;
}
if len_str2 == 0 {
return len_str1;... |
code/dynamic_programming/src/edit_distance/edit_distance_backtracking.cpp | // dynamic programming | edit distance | C++
// Part of Cosmos by OpenGenus Foundation
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <cmath>
class Alignment {
std::string sx, sy, sa, sb;
std::vector<std::vector<int>> A;
int sxL, syL;
int cost = 0;
//insertion ... |
code/dynamic_programming/src/edit_distance/edit_distance_hirschberg.cpp | /*
* dynamic programming | edit distance | C++
* Part of Cosmos by OpenGenus Foundation
*
* Dynamic-Programming + Divide & conquer for getting cost and aligned strings for problem of aligning two large strings
* Reference - Wikipedia-"Hirschberg's algorithm"
*/
#include <string>
#include <vector>
#include <iostr... |
code/dynamic_programming/src/egg_dropping_puzzle/README.md | # Egg Dropping Puzzle
## Description
For a `H`-floor building, we want to know which floors are
safe to drop eggs from without broking them and which floors
aren't. There are a few assumptions:
- An egg that survives a fall can be used again.
- A broken egg must be discarded.
- The effect of a fall is the same for a... |
code/dynamic_programming/src/egg_dropping_puzzle/egg_dropping_puzzle.c | #include <stdio.h>
#include <string.h>
#define min(a, b) (((a) < (b)) ? (a) : (b))
#define max(a, b) (((a) > (b)) ? (a) : (b))
#define MAX_EGGS 100
#define MAX_FLOORS 100
#define INF 1000000000
int memo[MAX_EGGS][MAX_FLOORS];
int
eggDrop(int n, int k)
{
if (k == 0)
return (0);
if (k == 1)
... |
code/dynamic_programming/src/egg_dropping_puzzle/egg_dropping_puzzle.cpp | /* Part of Cosmos by OpenGenus Foundation */
#include <iostream>
#define MAX_EGGS 100
#define MAX_FLOORS 100
#define INF 1000000000
using namespace std;
int memo[MAX_EGGS][MAX_FLOORS];
/*
* Returns the minimum number of attempts
* needed in the worst case for n eggs
* and k floors.
* Time complexity: O(n*k... |
code/dynamic_programming/src/egg_dropping_puzzle/egg_dropping_puzzle.cs | /* Part of Cosmos by OpenGenus Foundation */
using System;
class cosmos {
/* Function to get minimum number of */
/* trials needed in worst case with n */
/* eggs and k floors */
static int eggDrop(int n, int k)
{
// If there are no floors, then
// no trials needed. OR if there
// is one floor, one tri... |
code/dynamic_programming/src/egg_dropping_puzzle/egg_dropping_puzzle.hs | --- Part of Cosmos by OpenGenus Foundation
eggDropping :: Int -> Int -> Int
eggDropping floors eggs = d floors eggs
where m = floors
n = eggs
d floors' 1 = floors'
d 1 _ = 1
d 0 _ = 0
d _ 0 = error "No eggs left"
d floors' eggs' = minimum [1 + maximum [ table!(floor... |
code/dynamic_programming/src/egg_dropping_puzzle/egg_dropping_puzzle.py | # Part of Cosmos by the Open Genus Foundation
# A Dynamic Programming based Python Program for the Egg Dropping Puzzle
INT_MAX = 32767
def eggDrop(n, k):
eggFloor = [[0 for x in range(k + 1)] for x in range(n + 1)]
for i in range(1, n + 1):
eggFloor[i][1] = 1
eggFloor[i][0] = 0
# We alw... |
code/dynamic_programming/src/egg_dropping_puzzle/eggdroppingpuzzle.java |
//Dynamic Programming solution for the Egg Dropping Puzzle
/* Returns the minimum number of attempts
needed in the worst case for a eggs and b floors.*/
import java.util.*;
public class EggDroppingPuzzle {
// min trials with a eggs and b floors
private static int minTrials(int a, int b) {
int eggFloor[][]... |
code/dynamic_programming/src/factorial/factorial.c | #include <stdio.h>
int
factorial(int n)
{
if (n == 0 || n == 1)
return (1);
else
return (n * factorial(n - 1));
}
int
main()
{
int n;
printf("Enter a Whole Number: ");
scanf("%d", &n);
printf("%d! = %d\n", n, factorial(n));
return (0);
}
|
code/dynamic_programming/src/factorial/factorial.cpp | //Part of Cosmos by OpenGenus Foundation
#include <iostream>
using namespace std;
int factorial(int n)
{
//base case
if (n == 0 || n == 1)
{
return 1;
}
// recursive call
return (n * factorial(n - 1));
}
int main()
{
int n;
cout << "Enter a number";
//Taking input
cin >> n;
//printing output
... |
code/dynamic_programming/src/factorial/factorial.exs | defmodule Factorial do
def factorial(0), do: 1
def factorial(1), do: 1
def factorial(num) when num > 1 do
num * factorial(num - 1)
end
end
|
code/dynamic_programming/src/factorial/factorial.go | // Part of Cosmos by OpenGenus Foundation
package main
import "fmt"
func factorial(num int) int {
if num == 0 {
return 1
}
return (num * factorial(num-1))
}
func main() {
num := 5
fmt.Println(factorial(num))
}
|
code/dynamic_programming/src/factorial/factorial.java | /* Part of Cosmos by OpenGenus Foundation */
/**
* Implements factorial using recursion
*/
public class Factorial {
private static int factorial(int num) {
if (num == 0) {
return 1;
} else {
return (num * factorial(num - 1));
}
}
public static void main(S... |
code/dynamic_programming/src/factorial/factorial.js | function factorialize(number) {
if (number == 0) {
return 1;
} else {
return number * factorialize(number - 1);
}
}
factorialize(5);
/*replace the value of 5 with whatever value you
*want to find the factorial of
*/
|
code/dynamic_programming/src/factorial/factorial.md | ## Fibonacci Series implemented using dynamic programming
- If you do not know what **Fibonacci Series** is please [visit](https://iq.opengenus.org/calculate-n-fibonacci-number/) to get an idea about it.
- If you do not know what **dynamic programming** is please [visit](https://iq.opengenus.org/introduction-to-dynamic... |
code/dynamic_programming/src/factorial/factorial.py | # Part of Cosmos by OpenGenus Foundation
from functools import wraps
def memo(f):
"""Memoizing decorator for dynamic programming."""
@wraps(f)
def func(*args):
if args not in func.cache:
func.cache[args] = f(*args)
return func.cache[args]
func.cache = {}
return func
... |
code/dynamic_programming/src/factorial/factorial.rs | // Part of Cosmos by OpenGenus Foundation
fn factorial(n: u64) -> u64 {
match n {
0 => 1,
_ => n * factorial(n - 1)
}
}
fn main() {
for i in 1..10 {
println!("factorial({}) = {}", i, factorial(i));
}
}
|
code/dynamic_programming/src/factorial/factorial.scala | /* Part of Cosmos by OpenGenus Foundation */
import scala.annotation.tailrec
/**
* Implement factorial using tail recursion
*/
object main {
@tailrec
private def _factorial(of: Int, current: Int): Int = {
if (of == 0) {
current
} else {
_factorial(of - 1, of * current)
}
}
def fa... |
code/dynamic_programming/src/fibonacci/fibonacci.c | #include<stdio.h>
int fib(int n)
{
int f[n+2]; // 1 extra to handle case, n = 0
int i;
f[0] = 0;
f[1] = 1;
for (i = 2; i <= n; i++)
{
f[i] = f[i-1] + f[i-2];
}
return f[n];
}
int main ()
{
int n = 9;
printf("%d", fib(n));
getchar();
return 0;
}
|
code/dynamic_programming/src/fibonacci/fibonacci.cpp | // Part of Cosmos by OpenGenus
#include <iostream>
using namespace std;
int fib(int n)
{
int *ans = new int[n + 1]; //creating an array to store the outputs
ans[0] = 0;
ans[1] = 1;
for (int i = 2; i <= n; i++)
{
ans[i] = ans[i - 1] + ans[i - 2]; // storing outputs for further use
}
... |
code/dynamic_programming/src/fibonacci/fibonacci.exs | defmodule Fibonacci do
def fib(terms) do
if terms <= 0 do
{:error, :non_positive}
else
{fib_list, _} =
Enum.map_reduce(1..terms, {0, 1}, fn
1, _acc -> {1, {1, 1}}
_t, {n1, n2} -> {n1 + n2, {n1 + n2, n1}}
end)
Enum.each(fib_list, fn f -> IO.puts("#{f}") en... |
code/dynamic_programming/src/fibonacci/fibonacci.go | package dynamic
// NthFibonacci returns the nth Fibonacci Number
func NthFibonacci(n uint) uint {
if n == 0 {
return 0
}
// n1 and n2 are the (i-1)th and ith Fibonacci numbers, respectively
var n1, n2 uint = 0, 1
for i := uint(1); i < n; i++ {
n3 := n1 + n2
n1 = n2
n2 = n3
}
return n2
} |
code/dynamic_programming/src/fibonacci/fibonacci.java | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the Number:"); // taking input
int n = input.nextInt();
int output = fib(n);
System.out.println("Nth fibonacci no. is: " ... |
code/dynamic_programming/src/fibonacci/fibonacci.js | // Problem Statement(1): Find the nth Fibonacci number
// 1.a.Using Recusrion to find the nth fibonacci number
const FibonacciNumberRec = (num) => {
if (num <= 1)
return num;
return FibonacciNumberRec(num - 1) + FibonacciNumberRec(num - 2);
}
// 1.b.Using DP to find the nth fibonacci number
// fib[n]... |
code/dynamic_programming/src/fibonacci/fibonacci.md | ## Fibonacci Series implemented using dynamic programming
- If you do not know what **Fibonacci Series** is please [visit](https://iq.opengenus.org/calculate-n-fibonacci-number/) to get an idea about it.
- If you do not know what **dynamic programming** is please [visit](https://iq.opengenus.org/n-th-fibonacci-number-u... |
code/dynamic_programming/src/fibonacci/fibonacci.py | from sys import argv
def fibonacci(n):
"""
N'th fibonacci number using Dynamic Programming
"""
arr = [0, 1] # 1st two numbers as 0 and 1
while len(arr) < n + 1:
arr.append(0)
if n <= 1:
return n
else:
if arr[n - 1] == 0:
arr[n - 1] = fibonacci(n - 1)
... |
code/dynamic_programming/src/friends_pairing/friends_pairing.c | // Dynamic Programming solution to friends pairing problem in C
// Contributed by Santosh Vasisht
// Given n friends, each one can remain single or can be paired up with some other friend.
// Each friend can be paired only once.
// Find out the total number of ways in which friends can remain single or can be paired u... |
code/dynamic_programming/src/friends_pairing/friends_pairing.cpp | // Dynamic Programming solution to friends pairing problem in C++
// Contributed by Santosh Vasisht
// Given n friends, each one can remain single or can be paired up with some other friend.
// Each friend can be paired only once.
// Find out the total number of ways in which friends can remain single or can be paired... |
code/dynamic_programming/src/friends_pairing/friends_pairing.py | # Dynamic Programming solution to friends pairing problem in Python3
# Contributed by Santosh Vasisht
# Given n friends, each one can remain single or can be paired up with some other friend.
# Each friend can be paired only once.
# Find out the total number of ways in which friends can remain single or can be paired ... |
code/dynamic_programming/src/house_robber/HouseRobber.cpp | // Below is the solution of the same problem using C++
int rob(vector<int>& nums) {
if(nums.size()==0)
return 0;
if(nums.size()==1)
return nums[0];
int res[nums.size()];
res[0]=nums[0];
res[1]=max(nums[0],nums[1]);
... |
code/dynamic_programming/src/house_robber/HouseRobber.java | import java.util.Arrays;
class HouseRobber {
public static int rob(int[] nums) {
int len = nums.length;
if(len == 0) return 0;
if(len == 1) return nums[0];
if(len == 2) return Math.max(nums[0], nums[1]);
int memo[] = new int [len];
memo[0] = nums[0];
memo[1]... |
code/dynamic_programming/src/house_robber/HouseRobber.js | /**
* @param {number[]} nums
* @return {number}
*/
var rob = function(nums) {
// Tag: DP
const dp = [];
dp[0] = 0;
dp[1] = 0;
for (let i = 2; i < nums.length + 2; i++) {
dp[i] = Math.max(dp[i - 2] + nums[i - 2], dp[i - 1]);
}
return dp[nums.length + 1];
};
|
code/dynamic_programming/src/house_robber/README.md | # House Robber
## Description
Given a list of non-negative integers representing the amount of money in a house, determine the maximum amount of money a robber can rob tonight given that he cannot rob adjacent houses.
## Solution
e.g [1,2,3]<br>
Considering the constraint,<br>
robber has choice 1: houses with amoun... |
code/dynamic_programming/src/knapsack/Knapsack_DP_all3tech.cpp | ///////////////////////////////RECURSIVE APPROACH////////////////////////////////////////////////////////
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int knapSack(int W,int *wt,int *val,int n)
{
if(n==0||W==0)
{
return 0;
}
if(wt[n]<=W)
{
return max(val[n]+knapS... |
code/dynamic_programming/src/knapsack/README.md | # 0-1 Knapsack
## Description
Given `n` items, in which the `i`th item has weight `wi` and value `vi`,
find the maximum total value that can be put in a knapsack of capacity `W`.
You cannot break an item, either pick the complete item, or don't pick it.
## Solution
This is a dynamic programming algorithm.
We first ... |
code/dynamic_programming/src/knapsack/knapsack.c | #include <stdio.h>
// Part of Cosmos by OpenGenus Foundation
#define MAX 10
#define MAXIMUM(a, b) a > b ? a : b
void
Knapsack(int no, int wt, int pt[MAX], int weight[MAX])
{
int knap[MAX][MAX], x[MAX] = {0};
int i, j;
//For item
for (i = 0; i <=no; i++)
knap[i][0] = 0;
//For weight
for (i =... |
code/dynamic_programming/src/knapsack/knapsack.cpp | /*
*
* Part of Cosmos by OpenGenus Foundation
*
* Description:
* 1. We start with i = 0...N number of considered objects, where N is the
* total number of objects we have. Similarly, for the capacity of bag we
* go from b = 0...B where B is maximum capacity.
* 2. Now for each pair of (i, b) we compute... |
code/dynamic_programming/src/knapsack/knapsack.go | // Part of Cosmos by OpenGenus Foundation
package main
import "fmt"
/*
Exptected output:
The value list is [12 34 1 23 5 8 19 10]
The weight list is [5 4 3 7 6 5 1 6]
For maxWeight 20, the max value is 89
*/
func max(n1, n2 int) int {
if n1 > n2 {
return n1
}
return n2
}
func knapsack(value, weight []int, max... |
code/dynamic_programming/src/knapsack/knapsack.java | // Part of Cosmos by OpenGenus Foundation
class Knapsack {
public static void main(String[] args) throws Exception {
int val[] = {10, 40, 30, 50};
int wt[] = {5, 4, 6, 3};
int W = 10;
System.out.println(knapsack(val, wt, W));
}
public static int knapsack(int val[], int wt[],... |
code/dynamic_programming/src/knapsack/knapsack.js | /**
* Part of Cosmos by OpenGenus Foundation
*/
/**
* method which returns the maximum total value in the knapsack
* @param {array} valueArray
* @param {array} weightArray
* @param {integer} maximumWeight
*/
function knapsack(valueArray, weightArray, maximumWeight) {
let n = weightArray.length;
let matrix =... |
code/dynamic_programming/src/knapsack/knapsack.py | #######################################
# Part of Cosmos by OpenGenus Foundation
#######################################
def knapsack(weights, values, W):
n = len(weights)
# create 2d DP table with zeros to store intermediate values
tab = [[0 for i in range(W + 1)] for j in range(n + 1)]
# no furthe... |
code/dynamic_programming/src/largest_sum_contiguous_subarray/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/largest_sum_contiguous_subarray/largest_sum_contiguous_subarray.c | #include <stdio.h>
int
kadanesAlgorithm(int a[], int n)
{
int max_so_far = 0, max_ending_here = 0;
int i;
for (i = 0; i < n; ++i) {
max_ending_here = max_ending_here + a[i];
if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
if (max_ending_here < 0)
max_ending_here ... |
code/dynamic_programming/src/largest_sum_contiguous_subarray/largest_sum_contiguous_subarray.cpp | /*
* Part of Cosmos by OpenGenus Foundation
*
* BY:- https://github.com/alphaWizard
*
*/
#include <iostream>
#include <vector>
using namespace std;
int max_subarray_sum(const vector<int>& ar)
{
int msf = ar[0], mth = max(ar[0], 0);
size_t p = 0;
if (ar[0] < 0)
++p;
int maxi = ar[0];
... |
code/dynamic_programming/src/largest_sum_contiguous_subarray/largest_sum_contiguous_subarray.go | // Part of Cosmos by OpenGenus Foundation
package main
import "fmt"
func max(n1, n2 int) int {
if n1 > n2 {
return n1
}
return n2
}
func maxSubArraySum(data []int) int {
result := data[0]
current_max := max(data[0], 0)
for i := 1; i < len(data); i++ {
current_max += data[i]
result = max(result, current_... |
code/dynamic_programming/src/largest_sum_contiguous_subarray/largest_sum_contiguous_subarray.hs | module LargestSum where
-- Part of Cosmos by OpenGenus Foundation
sublists [] = []
sublists (a:as) = sublists as ++ [a]:(map (a:) (prefixes as))
suffixes [] = []
suffixes (x:xs) = (x:xs) : suffixes xs
prefixes x = map reverse $ (suffixes . reverse) x
largestSum = maximum . (map sum) . sublists
|
code/dynamic_programming/src/largest_sum_contiguous_subarray/largest_sum_contiguous_subarray.java | /* Part of Cosmos by OpenGenus Foundation */
import java.util.Scanner;
public class Max_subarray_problem {
public static void main(String[] args) {
System.out.println(new int[] {-3, 2, -1, 4, -5}, 0, 4); // Expected output: 5
System.out.println(new int[] {-1, -2, -3, -4, -5}, 0, 4); // Expect... |
code/dynamic_programming/src/largest_sum_contiguous_subarray/largest_sum_contiguous_subarray.py | # Part of Cosmos by OpenGenus Foundation
# Function to find the maximum contiguous subarray using Kadane's algorithm
def maxSubArraySum(a):
max_so_far = a[0]
max_ending_here = max(a[0], 0)
for i in range(1, len(a)):
max_ending_here += a[i]
max_so_far = max(max_so_far, max_ending_here)
... |
code/dynamic_programming/src/longest_bitonic_sequence/README.md | # Longest Bitonic Sequence
## Description
A bitonic sequence is a sequence of numbers which is first strictly increasing
then after a point strictly decreasing. Find the length of the longest bitonic
sequence in a given array `A`.
## Solution
This problem is a variation of the standard longest increasing subsequenc... |
code/dynamic_programming/src/longest_bitonic_sequence/longest_bitonic_sequence.c | /* Part of Cosmos by OpenGenus Foundation */
#include <stdio.h>
// helper function to get maximum of two integers
int
max(int a, int b)
{
return (a > b ? a : b);
}
/**
* Return the first element in v
* that is greater than or equal
* to x in O(log n).
*/
int
lower_bound(int v[], int n, int x)
{
... |
code/dynamic_programming/src/longest_bitonic_sequence/longest_bitonic_sequence.js | /**
* Part of Cosmos by OpenGenus Foundation
*/
/**
* Method that returns the subsequenceLengthArray 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;
... |
code/dynamic_programming/src/longest_bitonic_sequence/longest_bitonic_sequence.py | # Part of Cosmos by OpenGenus Foundation
import copy
# returns the longest increasing sequence
def longest_increasing_seq(numbers):
# longest increasing subsequence
lis = []
# base case
lis.append([numbers[0]])
# start filling using dp - forwards
for i in range(1, len(numbers)):
lis.... |
code/dynamic_programming/src/longest_bitonic_sequence/longestbitonicseq.cpp | #include <iostream>
#include <vector>
using namespace std;
// Part of Cosmos by OpenGenus Foundation
int lBitconSeq(vector<int> v, int n)
{
vector<int> lis, lds; // lis stands for longest increasing subsequence and lds stands for longest decreasing subsequence
if (n == 0)
return 0; // in case tha ar... |
code/dynamic_programming/src/longest_bitonic_sequence/longestbitonicsequence.java | /* Part of Cosmos by OpenGenus Foundation */
/* Dynamic Programming implementation in Java for longest bitonic
subsequence problem */
import java.util.*;
import java.lang.*;
import java.io.*;
class LBS
{
/* lbs() returns the length of the Longest Bitonic Subsequence in
arr[] of size n. The function mainly... |
code/dynamic_programming/src/longest_common_increasing_subsequence/longest_common_increasing_subsequence.cpp | /* Part of Cosmos by OpenGenus Foundation */
#include <iostream>
using namespace std;
int main()
{
int n, m, a[502] = {}, b[502] = {}, d[502][502] = {}, z = 0;
cin >> n >> m;
for (int i = 1; i <= n; i++)
cin >> a[i];
for (int i = 1; i <= m; i++)
cin >> b[i];
for (int i = 1; i <= n;... |
code/dynamic_programming/src/longest_common_subsequence/Printing_longest_common_subsequence.cpp | //Printing longest common sub-sequence
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
//Helper function to print LCA
string LCA(string s1,string s2){
int m=s1.length();
int n=s2.length();
int dp[m+1][n+1];
//initialising first row
for(int i=0; i<=m; i++){
dp[0][i]=0;
... |
code/dynamic_programming/src/longest_common_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/longest_common_subsequence/longest_common_subsequence.c | /*
Problem Statement :
Find the length of LCS present in given two sequences.
LCS -> Longest Common Subsequence
*/
#include <stdio.h>
#include <string.h>
#define MAX 1000
int max(int a, int b)
{
return (a > b) ? a : b;
}
int lcs(char *x, char *y, int x_len, int y_len)
{
int dp[x_len + 1][y_len + 1];
... |
code/dynamic_programming/src/longest_common_subsequence/longest_common_subsequence.cpp | /* Part of Cosmos by OpenGenus Foundation */
#include <iostream>
#include <string>
#include <cstring>
#define MAX 1010
using namespace std;
int memo[MAX][MAX];
/* Compute the longest common subsequence
* of strings a[0...n] and b[0...m]
* Time complexity: O(n*m)
*/
int lcs(const string& a, const string& b, i... |
code/dynamic_programming/src/longest_common_subsequence/longest_common_subsequence.cs | using System;
class LongestCommonSubsequence
{
static int longestCommonSubsequence(char[] x, char[] y)
{
int x_len = x.Length;
int y_len = y.Length;
int [,]dp = new int[x_len + 1, y_len + 1];
for (int i = 0; i <= x_len; i++)
{
for (int j = 0; j <= y_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.