买卖股票的最佳时机 IV -LintCode
2017-10-03 19:36
363 查看
假设你有一个数组,它的第i个元素是一支给定的股票在第i天的价格。
设计一个算法来找到最大的利润。你最多可以完成 k 笔交易。
注意事项:
你不可以同时参与多笔交易(你必须在再次购买前出售掉之前的股票)
样例:
给定价格 = [4,4,6,1,1,4,2,5], 且 k = 2, 返回 6.
挑战 :
O(nk) 时间序列。
思路见: http://blog.csdn.net/linhuanmars/article/details/23236995
设计一个算法来找到最大的利润。你最多可以完成 k 笔交易。
注意事项:
你不可以同时参与多笔交易(你必须在再次购买前出售掉之前的股票)
样例:
给定价格 = [4,4,6,1,1,4,2,5], 且 k = 2, 返回 6.
挑战 :
O(nk) 时间序列。
思路见: http://blog.csdn.net/linhuanmars/article/details/23236995
#ifndef C393_H #define C393_H #include<iostream> #include<vector> using namespace std; class Solution { public: /* * @param K: An integer * @param prices: An integer array * @return: Maximum profit */ int maxProfit(int K, vector<int> &prices) { // write your code here if (prices.empty()) return 0; int len = prices.size(); if (K > len / 2) { int max = 0; for (int i = 1; i < len; ++i) { int diff = prices[i] - prices[i - 1]; max += maxVal(0, diff); } return max; } vector<int> global(K + 1, 0); vector<int> local(K + 1, 0); for (int i = 0; i < len - 1; ++i) { int diff = prices[i + 1] - prices[i]; for (int j = K; j >= 1; --j) { local[j] = maxVal(global[j - 1] + maxVal(diff, 0), local[j] + diff); global[j] = maxVal(global[j], local[j]); } } return global[K]; } int maxVal(int a, int b) { return a > b ? a : b; } }; #endif
相关文章推荐
- LintCode 买卖股票的最佳时机I II III IV
- **[Lintcode]Best Time to Buy and Sell Stock IV 买卖股票的最佳时机 IV Leetcode
- lintcode:买卖股票的最佳时机 IV
- lintcode:买卖股票的最佳时机 II
- 买卖股票的最佳时机-LintCode
- 【LintCode】 Best Time to Buy and Sell Stock III 买卖股票的最佳时机 III
- lintcode-买卖股票的最佳时机-149
- 【LintCode】买卖股票的最佳时机
- 【LintCode】 Best Time to Buy and Sell Stock II 买卖股票的最佳时机 II
- lintcode-买卖股票的最佳时机II-150
- LintCode_149_买卖股票的最佳时机
- Lintcode 买卖股票的最佳时机 II
- LintCode 151 买卖股票的最佳时机 III
- 【LintCode】 Best Time to Buy and Sell Stock 买卖股票的最佳时机
- [Lintcode] #150 买卖股票的最佳时机 II
- lintcode--买卖股票的最佳时机
- lintcode-150-买卖股票的最佳时机 II
- 188. Best Time to Buy and Sell Stock IV(买卖股票的最佳时机 IV)
- LintCode 152 买卖股票的最佳时机 IV
- LintCode:买卖股票的最佳时机 II