标签:
Say you have an array for which the 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.
Solution:
典型的 dynamic programming
当 k(k=1000000000)很大时 申请过多内存会发生 runtime error
分两类情况处理。
1 int maxProfit(int k, vector<int> &prices) { 2 if (k > (prices.size() >> 1)) { 3 int maxm = 0; 4 for (int i = 0; i < (int)prices.size() - 1; ++i) { 5 if (prices[i+1] > prices[i]) { 6 maxm += prices[i+1] - prices[i]; 7 } 8 } 9 10 return maxm; 11 } 12 else { 13 int *dp = new int [((k << 1) | 1)]; 14 dp[0] = 0; 15 for (int i = 1; i <= (k<<1); ++i) { 16 dp[i] = INT_MIN; 17 } 18 for (int i = 0; i < prices.size(); ++i) { 19 for (int j = min(i+1, k<<1); j >= 1; --j) { 20 int v = j & 0x01 ? -prices[i] : prices[i]; 21 dp[j] = max(dp[j], dp[j-1] + v); 22 } 23 } 24 int maxm = 0; 25 for (int i = 1; i <= (k<<1); ++i) { 26 maxm = max(maxm, dp[i]); 27 } 28 29 delete[] dp; 30 return maxm; 31 }
LeetCode Best Time to Buy and Sell Stock IV
标签:
原文地址:http://www.cnblogs.com/liew/p/4395948.html