I will find an algorithm for this problem. Input: array of n integers and number k We must find a set of numbers from array, that product of all this numbers in set equals to k is I think, I must use dynamic programming for this task. But I have...

I am very new to the concept of Dynamic Programing and CS in general. I am teaching myself by reading lectures posted online, watching videos and solving problems posted on websites such as GeeksforGeeks and Hacker Rank. Problem Given input 3 25 30 5 where 3 = #of keys 25...

I am trying to solve a problem where I am given a nXn square matrix of characters and I want to find out size of the largest palindrome square from this? The largest palindrome square is, a square with all rows and all columns as palindrome. For eg. Input a...

I am aware of solutions that uses the bottom up dynamic programing approach to solve this problem in O(n^2). I am specifically looking for a top down dp approach. Is it possible to achieve longest palindromic substring using a recursive solution? Here is what I have tried but it fails...

I am reading Robert Sedgewick's algorithms 4th edition book, and he has the following task: Suppose that you have an N-story building and 2 eggs. Suppose also that an egg is broken if it is thrown off floor F or higher, and unbroken otherwise. Your cost model is the number...

I've been stuck on a problem for a while. I am in an algorithm course right now but this isn't a homework problem. We haven't gotten to dynamic programming in class yet, I'm just doing this on my own. Given a NxN sized checkerboard where every coordinate has a cost...

This question is an exact duplicate of: How to find the maximum number of pairs having difference less than a particular value? 1 answer I have a question in which I am given a set of values SET A, and a set of values SET B. I am supposed...

I have the following problem and I only have a slight idea about it: Consider a tape storage problem. Given n files of length l1,...,ln and frequencies with which they are accessed f1,...,fn, where sum of all frequencies is 1 and 0<fi<1. "Optimal" means to minimize the average retrieval time...

You are given an array of positive numbers and you need to find two disjoint sub sequences with minimum difference less than or equal to n. These sub sequences may or may not be contiguous For Example if array = [10,12,101,105,1000] and n = 10 Ans = [10,105] & [12,101]...

I am trying to understand a knapsack algorithm given to me in class, specifically the following pseudocode. This was my attempt to code it: //Init array var solution = []; var items = problem.items; var sackSize = problem.knapsack; solution[0] = 0; for(var k = 1; k <= sackSize; k++) {...

I am familiar with the 0-1 knapsack problem and when you are given a certain number of copies from each item but I can figure out how to solve it when you are given infinite copies of each item using dynamic programming. I am trying to solve it by hand...

I'm working on this Dynamic Programming problems, and I'm stuck on writing an iterative solution in Java The goal is to find the minimum number of calories it takes to spend exactly X cents. If we cannot spend exactly X cents then there is no solution. We are given N...

I am getting a matrix (from file.txt) of known size into the same size of 2D array. This code is fine for that. But now I am really looking for extending this, like getting a matrix of unknown size into a 2D array, i.e. using a dynamically sized 2D array....

I have interval data: A = (0,50) B = (20,500) C = (80,420) .... And realized that there's an associated graph with this data, the interval graph I'd like to find the most efficient path to go from A to G (assume I know all of the positive vertex weights,...

Can anyone explain me the dynamic algorithm, that finds number of subsets with sum equal to k. I searched in Google, but cant find any simple explanation! Sorry for my English! Here is the code: int numbers[MAX]; int GetmNumberOfSubsets() { int dp[MAX]; dp[0] = 1; int currentSum = 0; for...

The problem statement: Given a digit sequence, count the possible decodings of the given digit sequence. Examples: 12 gives 2 for: 'AB' and 'L' and 123 gives 3 for: 'ABC', 'LC' and 'AW' Here is my attempt: import java.util.*; public class decodingcount { static int calls = 0; static Map<Integer,...

I have a dynamic programming (possibly greedy) question. Let A be an mxn matrix. Let k be an integer such that k ≤ min{m,n}. Find k elements of A such that each of these k elements are in their unique column and row; and the sum of these k elements...

Given is a N*N grid.Now we need to find a good path of maximum length , where good path is defined as follow : Good path always start from a cell marked as 0 We are only allowed to move Left,Right,Up Or Down If the value of ith cell is...

The problem is as follows: Write a program that determines the number (modulo m) of white/black patterns on a 5*n square grid, which do not contain any of p forbidden patterns. The input data has the following format: the first row contains 3 comma separated integers: n - number of...

The following code traverses the list once and finds the LIS. I don't see why the DP algorithm should take O(n2). //C int lis(int *a, int l){ if(l == 0) return 1; else if(a[l] > a[l - 1]) return 1 + lis(a, l - 1); else return lis(a, l -...

How can i modify the below backtracking code which is used to display all the combinations of N digit binary number to display binary number which doesn't have consecutive 1's? example: Input: N = 2 Output: 3 // The 3 strings are 00, 01, 10 Input: N = 3 Output:...

Given a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, how many ways can we make the change? The order of coins doesn’t matter.There is additional restriction though: you...

I am working on the classic making change with coins problem with Python. This is my implementation. def memo(fn): def helper(*args): # here, * indicate the fn take arbitrary number of argumetns d = {} if args in d: return d[args] # args is a tuple, immutable, hashable else: res...

Task Given a list of numbers Eg: 1, 2, 3. Get every combination of these numbers using the operations of multiplication or addition (*/+) So in the above example the combinations would be 1+2+3 1+2*3 1*2*3 1*2+3 Ive written a basic recursive method to solve it, the way I thought...

Using this template class works perfectly fine when main operates with constructed variables of type dlring, yet my goal is to allow dynamic allocation, so I can handle a non-predefined number of doubly linked circular lists to allow usage of such functions as: Splitting a list into two by either...

Please note that this is required for a C# .NET 2.0 project (Linq not allowed). I know very similar questions have been asked here and I have already produce some working code (see below) but still would like an advice as to how to make the algorithm faster given k...

An agent is works between n producer and m consumers. ith producer, generates s_i candy and jth consumer consumes b_j candy in this year. For each candy that sales, agent get 1 dollar payoff. For some problems, one strict rule was defined that a producer should be sales candy to...

I need to solve the knapsack problem recursively, memoized and with dynamic programming. Currently I'm stuck at the memoized method (and partially the dynamic programming method). I adapted the code from what I found elsewhere on the internet. Currently the output is not correct. The problem involves profit and mass....

I am working on a problem that calculates the minimum number of traversals required in a binary search tree by arranging it the best way possible. I did come across a solution online, which I have understood, but I did some calculations of sample inputs by hand, and I did...

This is a homework problem and it is DP, but it is not a 'how many ways are there to reach the nth-stair problem'. Rather, in this problem each stair step is assigned a number from -10000 to 10000 so e.g. I have steps such as -1 2 1, and...

I got an extension method that gives me the value of every property in an instance. For scalar values works it fine. But for Collections there is a problem. This is my code: <Extension()> Public Function ToXml(Of T)(ByVal source As T) As XmlDocument Dim oXmlDocument As New XmlDocument oXmlDocument.AppendChild(oXmlDocument.CreateXmlDeclaration("1.0", "utf-8",...

I saw this pseudo-code on another stackoverflow question found here Split a string to a string of valid words using Dynamic Programming. The problem is a dynamic programming question to see if an input string can be split into words from a dictionary. The third line, means to set an...

I want to know for a problem say LCS, we can reduce space complexity for a dp solution because when we are filling the table in dp we just use either dp[i - 1][j] or dp[i][j - 1] to fill dp[i][j] as instead of having a dp table of size...

Running shortest path algorithm on a Directed Acyclic Graph (DAG) via dynamic programming which uses memoization has a runtime complexity of O(V + E) which can be verified using the following equation: d(s,v) = min{ d(s,u) + w(u,v) }, over all vertices u->v Now, Dijkstra's algorithm also requires the graph...

This question already has an answer here: Number of all increasing subsequences in given sequence? 5 answers Given an array A of size N I need to count such triplets (i,j,k) such that: Condition 1 : i < j < k Condition 2 : A[i] > A[j] > A[k]...

I am having issues with understanding dynamic programming solutions to various problems, specifically the coin change problem: "Given a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, how many...

Does anyone know how to answer this problem? I have been stuck for a few days trying to figure it out. A students decides to ride her bicycle from Vancouver to Halifax. She starts on the road at kilometer 0. Along the way there are n hotels H1, . ....

Can anyone walk me through this solution below? What does p mean? why its range j-1 to i? Thanks Given an array of integers and a number k, find k non-overlapping subarrays which have the largest sum. The number in each subarray should be contiguous. Return the largest sum. according...

Is this recurrence relation correct for the subset sum problem? Statement: Print Yes or No depending on whether there is a subset of the given array a[ ] which sums up to a given number n. dp[i][j] = true, if 0 to j elements in array sum up to i...

There is a classic Knapsack problem. My version of this problem is a little different. Given set of items, each with a mass, determine the number of combinations to pack items so that the total weight is less than or equal to a given limit. For example, there is 5...

The problem is: Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. For example, given s = "hithere", dict = ["hi", "there"]. Return true because "hithere" can be segmented as "leet code". My...

I had a technical phone interview and I was doing well until i was asked this question. I was totally lost i had very little idea on how to solve such a problem. You are given the following inputs: Total Score, Number of Players, Scores by each player. Sample Input...

Here is the problem: Given is an array A of n integers, a seperate integer M, and an integer d. Find a consecutive subarray S of A, such that the size of the subarray is less than or equal to d and the sum of all the elements in S...

I am trying to find a recurrence relation and algorithm to the following problem but have been stuck for a few days: There are a total of H > n hours in which to work on the n school projects (all of which are due at exactly the same time)...

Given the exact no. of elements that must be present in the array (let=r) and the max value of the last element of the array (let=n) find the total number of distinct non decreasing arrays possible (all elements of array must be >=0) Example- If r=3 and n=2 then some...

I was not really sure what this order of printing is called hence called it strange. Consider the following sample example: 1 3 5 2 6 7 Expected output: 1,2 1,6 1,7 3,2 3,6 3,7 5,2 5,6 5,7 Or this example: 1 2 3 4 5 6 7 8 9...

I am unable to find what's going wrong in both memotization and tabulation for spoj http://www.spoj.com/problems/CWC2015/.If you could point why both codes are giving respective errors that would be really helpful. 1--Memotization Error--time limit exceeded. Don't know why generated random cases and tested on ideone most of the solutions are...

In my algorithms course, there's a question in the book that goes as follows: "You are given an array a[1..n] of positive numbers and an integer k. You have to produce an array b[1..n], such that: for each j, b[j] is either 1 or 0. Array b has adjacent 1s...

I was trying to solve this problem but even after hours I am not able to understand the problem completely. I am not even able to come up with any brute force techniques.This is the question: There are N members and N problems and each member must exactly solve 1...

I am trying to solve this problem: A Professor of Physics gave projects to the students of his class. The students have to form a team of two for doing the project. The professor left the students to decide the teams. The number of students in a class will be...

I have been trying to write an algorithm to compute the maximum number or trials required in worst case, in the egg dropping problem. Here is my python code def eggDrop(n,k): eggFloor=[ [0 for i in range(k+1) ] ]* (n+1) for i in range(1, n+1): eggFloor[i][1] = 1 eggFloor[i][0] =...

The problem is: Jerry loses himself in the interesting game: Fruit Ninja. Fruit Ninja is a game of iPhone and iPad in which the players cut the fruits coming from the bottom of the screen and gain the bonus from cutting more than two fruits with a single slice. Once...

An interesting problem came up the other day. I have two data stream that is being output continuously. Say, A and B. (Different values) In the ideal world, A and B are exactly the opposite. If A increases by x percent, then B will decrease by x percent, and vice...

I was solving a problem on spoj. Problem has a simple recursive solution. Problem: Given an array of numbers of size n, select a set of numbers such that no two elements in the set are consecutive and sum of subset elements will be as close as possible to k,...

I am not able to figure out where is the DP first property of Overlapping subproblem fits in Subset Sum Problem. However, I understand the Optimal Substructure part.While doing the recursive solution of Including and excluding the element where are the problems getting overlapped? Is it like since it is...

Given the following Input 10 4 3 5 5 7 Where 10 = Total Score 4 = 4 players 3 = Score by player 1 5 = Score by player 2 5 = Score by player 3 7 = Score by player 4 I am to print players who's combine...

I am trying this problem on SPOJ. Its basically a 0/1 knapsack. Problem Statement: We are given N≤1000 choice of air tanks having oxygen capacity, nitrogen capacity, and weight O[i], N[i], and W[i] respectively O≤21,N≤79,W≤800. We need enough tanks to fuel t oxygen and a nitrogen respectively to complete the...

Given a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, how many ways can we make the change? The order of coins doesn’t matter. For example, for N =...

I am following a tutorial on dynamic programming.and following this link : http://www.8bitavenue.com/2011/11/dynamic-programming-maximum-contiguous-sub-sequence-sum/ they have derived a relation : M[j] = Max (A[j], A[j] + M[j-1]) but in the actual code while implementing this i cant undersatnd how they are using it .here is their implementation //Initialize the first value...

Suppose I have a string : x="AAAABBABAABCCABBCA" and I have the following information : AAA=1 ABB= ignore/remove from final output ABA=2 ABC=3 CAB=4 BCA= ignore/remove from final output so when I translate x the output y should be: y=1234 I tried: def fun(x): x=x.replace("AAA","1") x=x.replace("ABA","2") x=x.replace("ABB","") x=x.replace("ABC","3") x=x.replace("BCA","") x=x.replace("CAB","4") print...

Given an n-ary tree of integers, the task is to find the maximum sum of a subsequence with the constraint that no 2 numbers in the sequence should share a common edge in the tree. Example: 1 / \ 2 5 / \ 3 4 Maximum non adjacent sum =...

For example we have an array[]={1,3,2,7,4,6,8,9}. longest increasing subsequence of this array[]={1,3,4,6,8,9} and its length=6. longest decreasing subsequence of this array[]={3,2} and its length=2. Then is Bitonic subsequence of this array[]={1,3,4,6,8,9}? if Yes then its length=6.But length of Bitonic subsequence =length of lis + length of lds -1, here they...

Given the following Input 10 4 3 5 5 7 Where 10 = Total Score 4 = 4 players 3 = Score by player 1 5 = Score by player 2 5 = Score by player 3 7 = Score by player 4 Output should print the index of players...

In some parts of my Program I need to pass around a set of Objects (also some primitive types) between my classes. For every new combination I have to create a pretty "stupid" wrapper-class which just contains two or three fields. (int, String or today I've got a int, String,...

I am implementing the dynamic programming solution for copying books problem. The idea for the solution is taken from here and here. Problem statement: Before the invention of book-printing, it was very hard to make a copy of a book. All the contents had to be re-written by hand by...

Friends who can program "knapsack the dynamic programming method" and "C ++" Will share with me? Algorithm to solve knapsack with dynamic programming: Thank You all Code to the method of "weight / value" : #include <conio.h> #include <stdio.h> #include <iostream> #include <windows.h> using namespace std; void gotoxy(int x, int...

Interview Question: You are given N number in an array. A group of a numbers is a non-empty contiguous segment of array.The size of group is the number of numbers in that group. "A" is the minimum number in that group.Task was to find each x such that 1 <=...

Here is a problem I am stuck on: Two integers are given: N (the size of the array) and S (the required sum of all elements of the array) The requirements are to construct an array of size N and with the sum of its elements S in such a...

The Problem is making n cents change with quarters, dimes, nickels, and pennies, and using the least total number of coins. In the particular case where the four denominations are quarters,dimes, nickels, and pennies, we have c1 = 25, c2 = 10, c3 = 5, and c4 = 1. If...

Suppose I start with one pair of rabbit and each pair reproduces 3 pairs of rabbits. Let new rabbit pair be N and mature rabbit pair be M: N 0 M 1 MNNN 4 MNNN MMM MMM MMM 19 So the series is 0 1 4 19 How do we...

I want to know how can I best prepare for programming competitions:- 1)How much strong should my maths be? 2)What tools should I use? 3)Which language should I use? 4)How should I test my code? Please share any tips you have. Any help is greatly appreciated....

I need to find the largest triangle of ones in a matrix of zeros and ones using dynamic programming. So if this is my matrix: 1 0 0 1 1 0 1 1 1 1 0 1 1 1 0 1 1 1 1 1 1 1 0 0 1...

I know that: int fib(int n) { if (n == 0 || n == 1) return 1; return fib(n − 1)+ fib(n − 2); } when n=5，fib(5) evaluates as: fib(5) fib(4) + fib(3) (fib(3) + fib(2)) + (fib(2) + fib(1)) ((fib(2) + fib(1)) + (fib(1) + fib(0))) + ((fib(1) +...

The question is like this-- For every string given as input, you need to tell the number of subsequences of it that are palindromes (need not necessarily be distinct). Note that the empty string is not a palindrome. For example, the palindromic subsequences of "aab" are: "a", "a", "b", "aa",...

I am trying to learn the basics of Dynamic Programming (DP), and went through some the online resources i could get, such as... What is dynamic programming? Good examples, articles, books for understanding dynamic programming Tutorial for Dynamic Programming Dynamic Programming – From Novice to Advanced -- (I can't understand...

You have a number of stones with known weights w1, …, wn. Write a program that will rearrange the stones into two piles such that weight difference between the piles is minimal.

I'm getting Segmentation error for the code below. This is a solution to the SPOJ problem "Coins". I went through How to avoid SIGSEGV? and I made sure not to use uninitialized pointers, not to access out of memory etc (given n ≤ 109). I know that an array a[1000000000]...