[LeetCode] Best Time to Buy and keep Stock IV, leetcode=
Say you have an array for which Ith Element is the price of a given stock on day I .
Design an algorithm to find the maximum profit. You may complete at most k transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must encrypt the stock before you buy again ).
Solutions
Use Dynamic Planning to solve the problem.
We need to maintain the following two quantities:
global[i][j]
: Currently reachesi
Days at mostj
The maximum profit of the transaction.
local[i][j]
: Currently reachesi
Days at mostj
Transaction, and the last transaction was sold on the day, the maximum profit.
State transition equation:
global[i][j] = max(local[i][j], global[i-1][j])
The above equation compares the values of two quantities: ① the current local maximum value; ② the past global maximum value.
local[i][j] = max(global[i-1][j-1] + max(diff, 0), local[i-1][j] + diff)
The above equation compares the two quantities:
① Globali-1
Dayj-1
Next, add the current transaction (if today's transaction makes money ).
② Obtain the local numberi-1
Dayj
Next transaction, and then add the difference (local[i-1][j]
Yesi-1
Day-to-day transaction, which addsdiff
Afteri
Sales per day does not increase the number of transactions. Regardlessdiff
Both positive and negative values must be added; otherwise, they cannot be satisfied.local[i][j]
The condition that must be sold on the last day)
Another issue that needs to be noted is that when k is much larger than the array size, the above algorithm will become inefficient. Therefore, we can change it to an unlimited number of transactions.
Implementation Code
/*************************************** * ************************** @ Author: chu Xing * @ Date: 2015/2/22 * @ Status: Accepted * @ Runtime: 15 ms ************************************** * **************************/# include <iostream> # include <vector> # include <algorithm> using namespace std; class Solution {public: int maxProfit (int k, vector <int> & prices) {int len = prices. size (); if (len = 0) {return 0;} if (k> = len) {return helper (prices );} vector <int> max_local (k + 1, 0); vector <int> max_global (k + 1, 0); int diff; for (int I = 0; I <len-1; I ++) {diff = prices [I + 1]-prices [I]; for (int j = k; j> = 1; j --) {max_local [j] = max (max_global [j-1] + max (diff, 0), max_local [j] + diff ); max_global [j] = max (max_local [j], max_global [j]);} return max_global [k];} int helper (vector <int> & prices) {int profit = 0; for (int I = 0; I <prices. size ()-1; I ++) {profit = max (profit, profit + prices [I + 1]-prices [I]);} return profit ;}};