python,python-2.7,dynamic-programming

Here's a solution that will properly print 1234 when run over your string : x = "AAAABBABAABCCABBCA" newstr = '' for i in range(0,len(x),3): part = x[i:i + 3] if part == 'AAA': newstr += '1' elif part == 'ABA': newstr += '2' elif part == 'ABC': newstr += '3'...

algorithm,dynamic-programming,knapsack-problem

One possibility would be to provide a suitable number of multiplicities of the items. For item i, there can be at most m_i := K / w_i choices of that item, where K denotes the knapsack capacity and w_i denotes the weight of the i-th item. Furthermore, for each weight...

c#,arrays,multidimensional-array,dynamic-programming

An array is a fixed-sized data structure. It is well used in many languages. Unfortunately once created you may not modify its contents. That is, how do Lists resize? List is implemented with arrays, actually. So initially a list holds a fixed number of objects. When you want to add...

python,python-2.7,dynamic-programming

The process for a single step is to replace all 'M's with 'MNNN' and all 'N's with 'M', so: def step(state): return ''.join(['MNNN' if s == 'M' else 'M' for s in state]) For example: >>> s = 'N' >>> for _ in range(5): print s, len(s) s = step(s)...

algorithm,geometry,dynamic-programming,mathematical-optimization

You can for example model your problem as an assignment problem (Wikipedia link), where you define the cost C_ij of assigning point A_i (from set A) to point B_j (from set B) to be equal to the distance between them. This assignment problem can then be solved using the Hungarian...

arrays,algorithm,dynamic,dynamic-programming

Sum of first N positive value {1,2,3...N) is (N + 1)*N/2 So, we can easily come up with a formula for sum of N consecutive positive numbers (starting at a) ((N + a - 1) + a)*N/2 = (N + 2*a - 1)*N/2 Using binary search, we can find the...

algorithm,language-agnostic,dynamic-programming

Assuming that you can solve the following problem: Ending at cell (i, j) is there any palindrome with different length horizontally and vertically. Hint for above problem: boolean[][][]palindrome;//Is there any palindrome ending at (i , j) has length k for(int i = 0; i < n; i++){ for(int j =...

vb.net,reflection,extension-methods,dynamic-programming,generic-programming

In VB.NET, extension methods don't work on variables declared as Object for backward compatibility. Try: Dim instance As Object = new MyClass() instance.ToXml() It will fail. So you can't call ToXml on SubItem because SubItem is of type Object. You can, however, just call ToXml like a regular method: For...

algorithm,data-structures,dynamic-programming

I now see how to drop the solution time down to O(n^2). I'll leave my other answer up in case it's interesting as a stepping-stone to this one. Note: This is (also) only a solution to the first part of the problem; I see no way to efficiently count only...

c++,algorithm,dynamic-programming

The approach that you found doesn't work for the set of element consisting of 1, 2, and 5. As you said, for 1, 5, 5 the approach results in 4 operations (for the "coin change"), for example: 1, 5, 5 -> 1, 3, 5 -> 1, 1, 5 -> 1,...

c++,c,algorithm,dynamic-programming,knapsack-problem

To my understanding, you almost have the solution. If the recurrence relation is correct but too inefficient, you just have change the recursion to iteration. Apparently, you already have the array dp which represents the states and their respective values. Basically you should be able to solve fill dp with...

c,algorithm,dynamic-programming,brute-force

Although this is a one dimensional knastpsack problem, here is another mathematical way of doing this. Algorithm: 1D Optimization Input: weights (sequenc of weights) Output: left and right, two sequences with difference between sum of elements minimized *************************************************************************************** 1) Sort weights in descending order 2) initialize leftsum = 0, rightsum...

algorithm,search,dynamic-programming,binary-search,divide-and-conquer

Drop first egg from floors 1, 3, 6, ... (the partials sums of 1, 2, 3, ...). Then do linear search between last two floors.

c++,algorithm,dynamic-programming

with 999, you reach 11392 with 907, you reach 13120 and those numbers are out of bound. Live example...

IMHO, you need a strong knowledge in Maths, specially in algorithms. I don't think that this type of competitions are easy. If you want an idea, take a look on another year's challenges, for example here

algorithm,dynamic-programming,sub-arrays

What does p mean: just a iterator. (Chinese Algorithm Coder always like short name for variable...) Why its range j-1 to i: Indeed, dp analysis should be: d[i][j] = max{d[p][j-1]+maxSubArray(p+1,i)} j-1 <= p <= i-1 Why must p >= j-1? Because as dp[i][j] define: d[i][j] means the maximum sum we...

algorithm,combinations,dynamic-programming

This is one solution: items = [1,1,3,4,5] knapsack = [] limit = 7 def print_solutions(current_item, knapsack, current_sum): #if all items have been processed print the solution and return: if current_item == len(items): print knapsack return #don't take the current item and go check others print_solutions(current_item + 1, list(knapsack), current_sum) #take...

dynamic-programming,coin-change

You're making piles of coins for different values j, named M(j). The point of M(j - vi) is to consider a coin of value vi, then which pile do you add it to in order to reach the value j? The pile with value j - vi of course, because...

java,android,android-layout,layout,dynamic-programming

You pretty much did all the work by looping and inflating buttons into rows. Few adjustments and you're done: private void populateCategoryGrid() { TableLayout categoriesLayout; int category_count = 12; int NUM_ROW = category_count/3; int NUM_COL = category_count/4; LayoutInflater inflater = LayoutInflater.from(this); // Add rows for (int r=0;r<NUM_ROW;r++) { TableRow row...

algorithm,dynamic-programming,pseudocode

Yes, your idea is almost correct. Let's formalize it. Claim: f(i, j) is the size of the largest triangle with the right bottom corner at the (i, j) position and it is computed correctly. Proof: Let's use induction. The base case: for all cells in the first row and or...

c++11,linked-list,segmentation-fault,dynamic-programming

for(int i=0;i<k;i++) { while(!dlist[k].empty()) std::cout<<(dlist[k]).pop_back()<<" "; std::cout<<std::endl; } Is not using the iterator i. It should be: for(int i=0;i<k;i++) { while(!dlist[i].empty()) std::cout<<(dlist[i]).pop_back()<<" "; std::cout<<std::endl; } Since dlist is an array of size k, the original code produces an out-of-bounds access. Since the aforementioned loop makes every list in the...

The Fibonacci sequence example from wikipeadia gives a good example. Dynamic programming is an optimization technique that transforms a potentially exponential recursive solution into a polynomial time solution assuming the problem satisfies the principle of optimality. Basically meaning you can build an optimal solution from optimal sub-problems. In the example...

c++,algorithm,dynamic-programming

Why can't we use a similar approach in this question? It won't work because in the n stairs problem, the order is important. For e.g. if you are climbing 5 stairs, {1, 2, 1, 1} is counted as different to {1, 1, 2, 1}. However in the making change...

This is similar to the subset sum problem, where you are required to find a subset whom sum is a value k. Since there is a solution to your problem (you have a subset S whom multiplication is k) if and only if you have a subset of log(x) for...

java,algorithm,dynamic-programming

Ok, so after you have created and updated boolean array myArray. We will iterate from the last player to the first player, checking if we can use the current player in our final result int currentScore = total;//Maintain the current score. for(int i = lastPlayer ; i >= 0; i--){...

algorithm,math,statistics,dynamic-programming

I think you are looking for correlation coefficient remember last N values from both streams cyclic buffers are ideal for this compute the correlation coefficient detect the similarity drop for example like this: if (correlation_coefficient>-0.997) return "drop below 99.7%"; ...

c,algorithm,dynamic-programming

You are mistaken about the results to expect. Take your first example, with keys {1, 2, 3} and frequencies {10, 3, 1}; the optimal binary search tree is: 1 (10) \ 2 (3) \ 3 (1) (frequencies given in parentheses). The function returns the expected cost for seaching the tree...

c,dynamic-programming,memoization,knapsack-problem

So I know this is a homework question, so I won't give the the correct answer but I can say this: If a function is returning the same answer the second time it is run, it's usually because something hasn't been zeroed. There is some dirt left from the previous...

c++,algorithm,optimization,dynamic-programming

First of all, you are right that iteratively combining the best remaining student with the worst remaining student gives you the optimum result (see proof below). However, you don't calculate the cost of that solution correctly. You have to run through all pairs of your combination in order to find...

sql-server,view,sql-server-2008-r2,dynamic-programming

After working with some coworkers we came up with a solution to our problem. First of all there were too many keywords that we "didnt care about" so we thinned down the list. Even then we could have kept the list as is and just made this script longer. Created...

c++,dynamic-programming,fibonacci

In C++, the two solutions at your disposal that would save you time are the dynamic programming approach and the memoization approach. Dynamic Programming We just build a table from [1..n] and fill it in: int fib(int n) { if (n <= 1) return 1; std::vector<int> table(n + 1); table[0]...

Answer 2: A Static method means the function doesn't need any information from the object. The function just takes an input (in the parameters), processes it and returns something. When you don't see any "this" in a function, you can set it as static. Non-static methods usually read some properties...

c++,algorithm,recursion,dynamic-programming

Here's the final answer to the problem, following the contribution of @NiklasB. . Let w(x,y) denote the optimal partition of an array for the problem opt[x][y]. As follows, x <= w(x,y) < y. We assume that the positions for all subproblems opt[x][y] with a given subarray size d = y-x...

python,algorithm,dynamic-programming

This line is the problem: mapping = [(m + 1) * [0]] * (len(A) + 1) You're creating a list of lists, but you're not creating a unique inner list for each row - all of the rows are pointing to the same list (the one created by [(m +...

java,algorithm,dynamic-programming,recurrence

Not sure of your solution but here is an intuitive recursive approach with memoization. Let there be n books with ith book having pages[i] pages. Also let there be m subscribers. Also let dp[i][j] be the answer to problem if we were given only books i,i+1.....n and there are only...

algorithm,time-complexity,dynamic-programming,dijkstra

Dijkstra's Algorithm is not restricted to DAGs; it can be run on any graphs with no negative path weights, cyclic or otherwise. Topological sorting, that you most likely are referring to, fails the "arbitrary" clause of your Wiki quote.

algorithm,matrix,dynamic-programming

Greedy won't cut it. You need the Hungarian Algorithm machinery. One can think about creating n - k new rows and m - k new columns, making the new-row–new-column entries very unattractive and the other new entries very attractive. Then find a min-cost solution that matches the rows with the...

c++,algorithm,recursion,dynamic-programming,palindrome

For this case: if(S[x] == S[y]) ret = solve(x+1,y-1,val+2 - (x==y)); it should be: if(S[x] == S[y]) ret = max(solve(x + 1, y - 1, val + 2 - (x==y)), max(solve(x + 1, y, 0),solve(x, y - 1, 0))); Because, in case you cannot create a substring from x to...

python,dynamic-programming,memoization,python-decorators,coin-change

In your current code: def memo(fn): def helper(*args): d = {} you create a new "cache" dictionary d every time the decorated function is called. It's no wonder it's slower! The minimal fix is: def memo(fn): d = {} def helper(*args): but it could be neater generally. I use: def...

Actually this problem is not DP. It is a binary search problem. Do a binary search over the answer. For each number of bullet N, be greedy on each level. That is, out of the enemies that you can kill(i.e. have power no more than your current bullets), kill the...

The formula is correct and gives out 6 only... Consider the LIS[](as the LIS array) and LDS[] (as LDS array).. Now when you iterate from left to right you reach the position where LIS[index]=6 i.e. LIS till array[7] is 6.. Now LDS[index=7] is 1 (Trivially one element is the maximum...

c++,dynamic-programming,word-break

In your code, you are not using dynamic programming because you are not remembering the subproblems that you have already solved. You can enable this remembering, for example, by storing the results based on the starting position of the string s within the original string, or even based on its...

c++,dynamic-programming,divide-and-conquer

I answered a similar question 10 minutes ago. The ides here is the same: loop over sorted ranges. Here is the same code as in the other answer adapted to your problem (I just replaced the equality by a smaller-than relation): auto find_pairs(std::vector<int>& arr1, std::vector<int>& arr2, int diff) { std::vector<std::pair<int,int>...

algorithm,dynamic-programming,coin-change

Lets first talk about the number of ways, DP(m,n) = DP(m-1, n) + DP(m, n-Sm). This in indeed correct because either you can use the mth denomination or you can avoid it. Now you say why don't we write it as DP[i] = DP[i-d1]+DP[i-d2]+...DP[i-dn]. Well this will lead to...

java,dynamic-programming,fibonacci

Basically int[] fib is a cache in which the ith fibonacci number is stored. This is a great time saver. Otherwise the recursive fibonacci procedure would need to recalculate a lot of values. E.g. fib[8] = fibonacci(7) + fibonacci(6) But then: fib[7] = fibonacci(6) + fibonacci(5) As you can see,...

dynamic-programming,recurrence-relation,subset-sum

You are almost correct ( not sure why you used min ). But let dp[i][j] store the answer of whether a subset of arr[0],arr[1],....arr[j] (here arr[] is the array of elements ) can sum upto i. That is dp[i][j] is 1 if answer is yes and 0 if answer is...

c++,arrays,logic,dynamic-programming

The answer to your question is already given in this line: //M[j-1] + A[j] > A[j] is equivalent to M[j-1] > 0 The if statement chooses the bigger value between A[j] and M[j-1]+A[j]. Would this be more clear to you? if (M[j-1] + A[j] > A[j]) // is exact the...

No. If all the costs are integers, at each cell you need to store at most O(M) elements. So you need O(MN^2) memory. If the sum is >M you just ignore it. In this paper there is a mention of a pseudo polynomial algorithm to solve similar problem (exact cost)....

dynamic-programming,recurrence,recurrence-relation

I don't really understand your recurrence relation: Let dp[i][j][k] represent sum up to i with j elements and k coins. I think you're on the right track, but I suggest simply dropping the middle dimension [j], and use dp[sum][coinsLeft] as follows: dp[0][0] = 1 // coins: 0, desired sum: 0...

c,algorithm,recursion,dynamic-programming,backtracking

Don't place a '1' if the previous position is also '1'. For example: if (count == 0 || target[count-1] != '1') { target[count] = '1'; foo(size, count+1); } ...

python,algorithm,recursion,dynamic-programming,memoization

All paths arrive in a cell either from above or from left. If you loop through the grid left to right and top to bottom, you can accumulate the sums from cells you have computed already. The idea is the same as in TravisJ's answer. def gridsums(grid): previous_row_sums = [set()...

The problem is in this line: eggFloor=[ [0 for i in range(k+1) ] ]* (n+1) You want this to create a list containing (n+1) lists of (k+1) zeroes. What the * (n+1) does is slightly different - it creates a list containing (n+1) copies of the same list. This is...

algorithm,tree,dynamic-programming

This problem is pretty standard: Let's store the number of prefix sums that have a given remainder modulo 3 in each node: class Node { int[] withRemainder = new int[3]; int totalSum; } The base case(for a leaf) is obvious: totalSum is just the value of the digit modulo 3...

algorithm,recursion,call,dynamic-programming,memoization

@AndyG's comment is pretty much on the point here. I also like @shebang's answer, but here's one that directly answers these questions in this context, not through reduction to another problem. It's just not clear what a top-down, breadth-first solution would look like. But even if you somehow paused the...

python,text,dynamic-programming

Note that the word list contains all 26 individual letters as words. With just the following modifications, your algorithm will correctly infer the spaces for the input string "therearesevendeadlysins" (i.e. "7" changed to "seven"): Remove the single letter words from the word list (perhaps except for "a" and "i".) As...

arrays,algorithm,dynamic,dynamic-programming

M[i, j] is max sum from 1 to i, with j adjacent 1s The answer we need is M[n, k] which can be computed as the max of 3 situations: a[i]=0 => S=M[i-1, j] a[i]=1 and a[i-1]=0 => S=M[i-2, j]+a[i] a[i]=1 and a[i-1]=1 => S=M[i-1, j-1]+a[i] so the recursive rule...

java,algorithm,dynamic-programming

First note that table[i] is number of ways for coin change when N=i. Given Algorithm fills this array (table[]) as per given set of coin (S[]). Initially all values in table[] are initialized to 0. And table[0] set to 0 (this is base case N=0). Each coin adds up values...

c++,debugging,dynamic-programming

I've managed to fix the problem myself (though PaulMcKenzie deserves a big thank you for sending me in the right direction). The problem was that my algorithm did not distinguish between forbidden patterns that were shifted by 0, 1 or 2 bits to left. When input data only had patterns...

I think this would work: G[H<0, j] = -Infinity G[H, 0] = 0 G[H, j] = max(G[H-i, j-1]+f_j(i)) for 0<=i<=H In the recurrence I'm trying to find the best number of hours to work on the project j. This solution is O(H^2*n)....

dynamic-programming,knapsack-problem

Hasty judgment! I am sorry for some people! My problem, I replied: #include <iostream> #include <string> using namespace std; void main(){ // Ali Aghajani 2015/06/08 int i, w, W, n, p[50][2], B[50][50]; string R[50][50]; char end = 'y'; while (end == 'y' || end == 'Y'){ system("cls"); cout << "Enter...

Dynamic programming as you know is all about asking the right questions. Questions that should be asked here with an example: a = [-5, -2, 1, 3] What is the maximum value you can get if you step on 2 step(array index starting from zero) whose value is 1? Let's...

In dynamic programming a given problems has Optimal Substructure Property if optimal solution of the given problem can be obtained by using optimal solutions of its sub problems. For example the shortest path problem has following optimal substructure property: If a node X lies in the shortest path from a...

algorithm,tree,dynamic-programming,maximize

Lets say dp[u][select] stores the answer: maximum sub sequence sum with no two nodes having edge such that we consider only the sub-tree rooted at node u ( such that u is selected or not ). Now you can write a recursive program where state of each recursion is (u,select)...

algorithm,recursion,data-structures,dynamic-programming

Let's call the entire set of numbers S = {s[1], ...., s[n]}, the target value k, and write f(X, t) = 1 if there is a subset of X that sums to t, and 0 otherwise. So the answer we want to calculate is f(S, k). You will get overlapping...

java,wrapper,dynamic-programming,dynamic-proxy

As i meantion in comments, consider to use generic. You need to have object which holds two custom types, here we go: class Pair<F,S> { private F first; private S second; Pair(F first, S second){ this.first = first; this.second= second; } public F getFirst(){ return first; } public S getSecond(){...

c++,algorithm,dynamic-programming

Your DP solution should be 2-dimensional, 1 dimension for the sum, and 1 dimension for the number of elements. The recursive formula defining this solution is: DP(x,i) = 0 x < 0 DP(0,i) = 1 DP(x,0) = 0 x > 0 DP(x,i) = DP(x-numbers[i],i-1) + DP(x,i-1) And it should be...

c++,algorithm,dynamic-programming

It's probably wrong when there is some segments having same start time. I run this test case with your code: 10 1 1 1 2 3 3 1 4 3 5 3 6 3 7 8 8 3 9 3 10 Your code output 10 but the answer is actually...

algorithm,search,optimization,dynamic-programming,linear-programming

Assuming that you are allowed to have fractional grams of food items, you can solve this problem analytically, see http://en.wikipedia.org/wiki/Linear_least_squares_%28mathematics%29 for details. You have the additional implicit constraint that none of the foods can be present in negative amount. So if foods appear in a negative amount, you will need...

algorithm,math,graph,dynamic-programming,graph-algorithm

To my understanding, the problem can be solved as a Maximum Bipartite Matching, however the modelling requires the graph to be relatively large compared to the original input; for every feasible edge (s_i,b_j) introduce s_i nodes for the producer partition and b_j for the consumer partition and connect each producer...

javascript,algorithm,dynamic-programming,knapsack-problem

You want to look at each element of the items array. The first element is items[0] and the last element is items[items.length-1]. Therefore, you should change the line for (var i = 1; i <= items.length; i++) to this: for (var i = 0; i < items.length; i++) Now items[i].weight...

java,algorithm,recursion,dynamic-programming

This is the subset sum problem, and assuming your scores are relatively small integers, it can be solved in pseudo-polynomial time using DP: D(i,0) = 1 D(0,x) = 0 x > 0 D(i,x) = D(i-1, x) + D(i-1, x-arr[i]) The above recursion formulas will generate the matrix of size total_score...

This reminds me of Huffman coding. I am not sure if the following approach is optimal, but it will probably give a good answer in practice. Pick the easiest two problems T0 and T1 and replace them by a single problem consisting of time D+max(T0,T1). Repeat until you have a...

algorithm,math,dynamic-programming

Let's take some non-decreasing sequence which qualifies, and encode it using 0s and 1s. The decoding algorithm is simple: Set the_value to 0 For each element in the coded sequence: If the element is 0, output the_value. If the element is 1, add 1 to the_value. Now, I claim that...

algorithm,graph,dynamic-programming,directed-acyclic-graphs

Imagine that there is a directed edge between two states if we can go from the first state to the second one(of course, a state can consist of several parameters). There are no cycles in this graph, so it is DAG. So visualizing a DAG itself is not hard(you can...

c,algorithm,dynamic-programming,knapsack-problem

The problem is that you are assigning infinite weight (cost) to all cases that use 0 tanks -- including, incorrectly, the case where oxy = nit = 0. In that case (i.e. dp[0][0][0]) the weight assigned should be 0, since you can supply 0 oxygen and 0 nitrogen quite comfortably...

algorithm,dynamic-programming,combinatorics,subsequence

If the sum of all your elements is not too big (within millions), then you can do a solution similar to a knapsack problem. Your DP state is a difference between two sets, and for every element you iterate over all the differences you know so far, and update them....

dynamic-programming,memoization

The simple answer is NO In bottom Up you can remove the Rows which are unnecessary just because you know those rows would not be used again.... In Memoization , Recursion calls in any order rather than a complete formal method for example: there is a call from LCS(i,j) to...

c,algorithm,dynamic-programming

The function you presented does have a keys parameter, but it does not use it. You could remove it altogether. Edit: in particular, since function optimalSearchTree() does not use its keys parameter at all, removing that argument requires changing only the function signature (... int optimalSearchTree(int freq[], int n) ...)...

c#,algorithm,.net-2.0,dynamic-programming,subset-sum

My previous answer works on the principle of cutting off the number of combinations to check. But this can be improved significantly once you sort the array. The principle is similar, but since the solution is entirely different, I've decided to put it in a separate answer. I was careful...

dynamic,dynamic-programming,pseudocode

It's confusing syntax, and I'm pretty sure there's a mistake. It should be: for i in range(N - 1, 0, -1) //0, not -1 which I believe means for i from (N - 1) downto 0 //-1 was the step, like i-- or i -= 1 This makes sense with...

java,algorithm,recursion,dynamic-programming

Working code: private static int decode(String str) { construct(); int n = str.length(); int[] count = new int[n]; count[0] = 1; for (int i = 1; i < n; i++) { String x = codes.get(Integer.parseInt(str.substring(i, i + 1))); if (str.charAt(i) != '0') count[i] = count[i - 1]; if (Integer.parseInt(str.substring(i -...

algorithm,graph,dynamic-programming,graph-theory,networkx

If you must go from A to G in an efficient way, you aren't looking for a minimum spanning tree algorithm. A simple shortest path algorithm is enough. You just have to adapt you graph to put the weights in the edges instead of the nodes. But it's just a...

algorithm,erlang,dynamic-programming,combinatorics,lis

Your current implementation of lis/1 function is O(n), I don't see any reasons to doubt. But there is some problem. You implementation doesn't actually calculate valid LIS. Try lis(lists:reverse([1,2,3,4,1,2])) for error example. Longest increasing sequense is [1,2,3,4], right? But your algorith returns 6 as result. First error in your algorithm...

c++,segmentation-fault,maps,dynamic-programming

You get SIGSEGV on dp(0) call. It causes an infinite recursion. By the way, your solution is wrong, for example the answer for 24 is not 25. Try to avoid magic constants, it is just enough to set a[0] = 0 and make a more accurate dp function: uint32_t dp(uint32_t...

scala,dynamic-programming,memoization

This is a modified version of your code that uses match and case def uniquePathsMemoization(n:Int, m:Int, row:Int, col:Int, seen:Array[Array[Int]]):Int = (row,col) match{ case (row,col) if row == m && col == n => 1 case (row,col) if row > m || col > n => 0 case (row,col) => if...

algorithm,dynamic-programming,memoization,subset-sum

Suggestion: The way you are solving will not work because of complexity. Although space complexity will work (limit is 1536MB and space used is around 785MB), but time complexity is too high for time limit of 5s. An estimate is 10^8 could be executed safely within 1 sec. If you...

java,algorithm,recursion,permutation,dynamic-programming

I think your mistake is that you pass a single operator to the function permutateSigns instead of giving all operators. Therefore you call the same function twice at the beginning, which results in doubled answers. Here is the corrected code (I think it is what you need) public class ArithmeticGame...

c++,algorithm,dynamic-programming

First, sort the array, maintain the index of each element. class Node{ int index, val; } For comparing two nodes, we first need to compare their values. If the values equals, we will compare their index, consider a node is greater if its index is smaller. Now, process each node...

Very brief sketch of a linear-time solution: for each array element, compute the size of the maximal group for which that element is the minimum. (Break ties by treating the first of two equal elements as lesser.) Sort the elements by their associated size, in linear time using a degenerate...

java,dynamic-programming,knapsack-problem

The recurrence relationship will be the same, it doesn't matter if you are programming it top down or bottom up. Since you have looked upon http://en.wikipedia.org/wiki/Knapsack_problem the recurrence relation will remain the same. Only change is that in general in Knapsack problem you are given a limit (weight limit) and...

algorithm,optimization,dynamic-programming,frequency

There is no need for Dynamic Programming for this problem. It is a simple sorting problem, with a slight twist. Find frequency / length for each file. This gets you, how frequent is each unit length access for the file. Sort these in descending order since each file is "penalized"...

c++,algorithm,recursion,dynamic-programming

This problem is a variation of Longest Path Problem, however your restrictions make this problem much easier, since the graph is actually a Directed Acyclic Graph (DAG), and thus the problem is solveable efficiently. Define the directed graph G=(V,E) as following: V = { all cells in the matrix} (sanity...

arrays,algorithm,dynamic-programming

If all numbers are non-negative, this has a straightforward O(N) solution. The requirement of length<=d doesn't add any complexity, just add a check current_length<=d. I assume there are negative numbers in the array. We need additional O(N) space. Compute prefix-sum of each index of S: p(i) = sum(S,0,i). Place p(i)...

c++,algorithm,recursion,dynamic-programming

As you said, there are rows^columns things to physically print out in the algorithm so you can't do better than an O(rows^columns) algorithm and your algorithm is as optimal as you'll get.

java,algorithm,recursion,dynamic-programming,subset

Here's the super naive solution that simply generates a power set on your input array and then iterates over each set to see if the sum satisfies the given total. I hacked it together with code already available on StackOverflow. O(2n) in time and space. Gross. You can use the...