Say you have an array for which thei_th element is the price of a given stock on day_i.
Design an algorithm to find the maximum profit. You may complete at mostk
transactions.
Notice
You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
Have you met this question in a real interview?
Yes
Example
Given prices =[4,4,6,1,1,4,2,5]
, and k =2
, return6
.
O(nk) time.
class Solution {
public:
/\*\*
\* @param k: An integer
\* @param prices: Given an integer array
\* @return: Maximum profit
\*/
int maxProfit\(int k, vector<int> &prices\) {
// write your code here
if \(k == 0 \|\| prices.empty\(\)\) {
return 0;
}
int n = prices.size\(\);
if \(k >= n / 2\) {
int ans = 0;
for \(int i = 1; i < n; ++i\) {
if \(prices\[i\] > prices\[i - 1\]\) {
ans += \(prices\[i\] - prices\[i - 1\]\);
}
}
return ans;
}
vector<vector<int>> f\(k + 1, vector<int>\(n, 0\)\);
for \(int i = 1; i <= k; ++i\) {
int localMax = f\[i - 1\]\[0\] - prices\[0\];
for \(int j = 1; j < n; ++j\) {
f\[i\]\[j\] = max\(f\[i\]\[j - 1\], prices\[j\] + localMax\);
localMax = std::max\(localMax, f\[i - 1\]\[j\] - prices\[j\]\);
}
}
return f\[k\]\[n - 1\];
}
};