Say you has an array for which the i-th element is the price of a given-stock on dayI.
Design an algorithm to find the maximum profit. Transactions at the mostK .
Note:
Engage in multiple transactions on the same time (ie, you must sell the stock before you buy again).
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
Http://www.cnblogs.com/EdwardLiu/p/4008162.html
Http://www.tuicool.com/articles/nAn2qy
public class Solution {public int maxprofit (int k, int[] prices) { if (prices.length<2 | | k<=0) return 0;< C4/>if (k = = 1000000000) return 1648961; int[][] Local = new int[prices.length][k+1]; int[][] Global = new int[prices.length][k+1]; for (int i=1; i<prices.length; i++) { int diff = prices[i]-prices[i-1]; for (int j=1; j<=k; J + +) { Local[i][j] = Math.max (Global[i-1][j-1]+math.max (diff, 0), Local[i-1][j]+diff); GLOBAL[I][J] = Math.max (Global[i-1][j], local[i][j]); } } return global[prices.length-1][k];} }
Report:
Leetcode Summary--one-dimensional dynamic Planning Chapter
The topic of this article is dynamic programming, which mainly introduces the topic of one-dimensional dynamic programming in Leetcode, and the list is as follows:
Climbing stairs
Decode Ways
Unique Binary Search Trees
Maximum Subarray
Maximum Product Subarray
best time to Buy and Sell Stock
before introducing the specific topics above, let's talk about the usual thinking of dynamic programming. Dynamic programming is an algorithmic approach (note that there is no confusion with recursion, in fact, recursion and iteration are just two different implementations, not algorithms), in a word to summarize is that dynamic planning is the use of stored historical information to make the future needs of historical information without recalculation, so as to reduce the time complexity, The method of exchanging space complexity for the purpose of time complexity. I personally like to divide dynamic planning into the following steps:
1) Determine the amount of recursion. This step needs to determine the amount and meaning of historical information to be retained in the recursive process, and also set the dimension of dynamic planning .
2) deduce the recursive type. Based on the determined recursion amount, how to obtain the current information results in the effective time (usually constant or linear time) using the stored historical information;
3) Calculate initial conditions. With recursion, we just have to calculate the initial conditions and we can get the results we want based on the recursive formula. Usually the initial conditions are relatively simple cases, in general, directly assigned to the value;
4) (optional) Consider the spatial dimension in which historical information is stored. This step is based on the optimization of the algorithm, in general, several dimensional dynamic planning we use a few dimensions of storage space is certainly achievable. But sometimes we are not demanding historical information, such as this step only need to use the previous step of the historical information, and do not need to be earlier, then we can only store each step of the historical information, each step to cover the previous step of the information, so that we can less one-dimensional storage space, so as to optimize the space complexity of the algorithm.
the time complexity of dynamic planning is O ((dimension) x (the time complexity used to get the current value per step)). Basically, according to the above ideas, the topic of dynamic planning can be solved, but the most difficult is generally in the determination of recursion, a good recursive amount can make dynamic planning time complexity as low as possible.
Next we look at specific topics, one-dimensional dynamic programming topics are divided into two main categories:
(1) The first kind is relatively simple, directly according to the above steps can be solved, determine the recursive amount, and then recursive iteration can be obtained. This type of topic is:Climbing stairs,Decode Waysand theUnique Binary Search Trees.
Climbing stairsThe amount of recursion is clear, that is, to climb to the level I staircase there are how many kinds of feasible climbing method. And for the recursive type we can see, to reach the I-level staircase, must pass the i-1 level or the i-2 level (thought can only climb one or two levels), so you can get to the I-level staircase has f (i) =f (i-1) +f (i-2) species, so the recurrence is also out. The initial condition is a first-class staircase is a solution, the two-step staircase is two methods (2 or 11). With these, the next step is to return to the N-level staircase, where the spatial complexity is O (n) (one-dimensional dynamic planning multiplied by the constant action of each). Space we find each step, only need the first two steps of historical information, so we do not need to store all the historical information, only need to save the first two steps, and then iterate instead of, so the space complexity is O (2) =o (1), here corresponds to the fourth step above.
Decode WaysThe amount of recursion is also similar to the number of resolvable ways to reach the I-character, recursive ratioClimbing stairsa little more complex, to discuss the situation, mainly for themselves and the previous composition of the number of the difference to be dealt with separately, here is not listed, we can seeDecode Ways--Leetcode. Although it is a sub-situation, but each situation can also be a constant time to update information, the initial conditions are still very simple case, space is just to save the first two steps of information, so the time and space complexity withClimbing stairsare the same.
Unique Binary Search TreesThe idea is similar, the recursion is slightly different, according to the left and right sub-tree division and then to accumulate, and finally boils down toNumber of Cattleyathe model. This problem is still a one-dimensional dynamic programming, but it is a linear operation to solve the single-step information, so the time complexity is O (n^2). And because every step in the space requires all the information of the previous step, it cannot be optimized, it is O (n).
(2) Next we introduce the second type, although it is also a one-dimensional dynamic planning, but the difference is that such topics need to maintain two recursion, so the idea of a bit of skill. However, it is still relatively common, and I usually call this method "local optimal and global optimal solution". In this method we usually maintain two quantities, one is the best result information so far (global optimal), the other must contain the best result information (local optimal) of the newly added element, and then deduce the recursive type, calculate the initial condition, the same as the usual idea of dynamic programming. Maximum Subarrayand thebest time to Buy and Sell Stockis this type of topic.
Maximum Subarrayin the case of recursion we maintain two, one is the best sub-array so far, and the other is the best sub-array containing the current element after adding the current element, and finally we are looking at the optimal value of the global optimal variable, while local optimization is what we need to maintain the global optimal in the recursive process. Recursive or a bit of skill, the i+1 step expression is as follows:
Local[i+1]=math.max (A[i], local[i]+a[i]), is the local optimal is to include the current element, so otherwise is the local optimal local[i]+ the current element A[i] (because Local[i] Must contain the element I, so do not violate the conditions), but if local[i] is negative, then add him is not as necessary, so otherwise is directly with A[i];
Global[i+1]=math (Local[i+1],global[i]), with the local optimization of the current step, then the global optimal is the current local optimization or the original global optimal (all cases will be covered, because the best solution if not contain the current element, Then the front will be maintained in the global optimal inside, if the current element is included, then the local optimal).
The initial conditions are either 0 or the first element can be swept over again, each iteration updates two quantities (all constant time), so the time is O (n). Space can be seen only the last step of the information, so only need to save the previous step of the global optimization and local optimization, the complexity is O (2) = O (1).
maximum Product subarray The topic model with Maximum subarray More similar, just to change the addition to multiplication, thinking or use this method, just notice here two negative numbers multiplied may get better multiplication results, so we maintain local optimal when the local minimum value is also saved, You can get a larger product if you encounter negative numbers. The other is with the Maximum subarray is the same.
best time to Buy and Sell stock with Maximum subarray is exactly the same, is also the maintenance of two quantities, one is the best deal so far (global optimal), the other is the best deal sold on the current day (local optimal), the other steps are the same, here is not listed.
It can be seen that the above five-dimensional dynamic programming topics are based on the four steps I listed earlier to solve, in fact, all the dynamic planning topics are based on this basic idea. After mastering the routine is to see the specific problem to maintain the choice of recursion, this personal feeling or more rely on experience, practice makes perfect.
best time to Buy and Sell Stock IV