算法设计与应用基础
来源:互联网 发布:飞鸽传书网络连接失败 编辑:程序博客网 时间:2024/06/07 03:01
188. Best Time to Buy and Sell Stock IV
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.
Note:
You may not engage in multiple transactions at 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.
Subscribe to see which companies asked this question.
设计利润最大化算法。您最多可以完成k个事务。
注:
你不能同时进行多个交易(你必须在卖出股票之前再购买)。
这题比较有难度,需要熟练掌握向量的运用才能解答
class Solution {
public:
int maxProfit(int k, vector<int> &prices) {
int len = prices.size();
if (len<2) return 0;
if (k>len/2){ // simple case
int ans = 0;
for (int i=1; i<len; ++i){
ans += max(prices[i] - prices[i-1],0);
}
return ans;
}
int hold[k+1];
int rele[k+1];
for (int i=0;i<=k;++i){
hold[i] = INT_MIN;
rele[i] = 0;
}
int cur;
for (int i=0; i<len; ++i){
cur = prices[i];
for(int j=k; j>0; --j){
rele[j] = max(rele[j],hold[j] + cur);
hold[j] = max(hold[j],rele[j-1] - cur);
}
}
return rele[k];
}
};
- 算法设计与应用基础
- 算法设计与应用基础
- 算法设计与应用基础
- 算法设计与应用基础
- 算法设计与应用基础
- 算法设计与应用基础
- 算法设计与应用基础
- 算法设计与应用基础
- 算法设计与应用基础
- 算法设计与应用基础
- 算法设计与应用基础
- 算法设计与应用基础
- 算法设计与应用基础
- 算法设计与应用基础
- 算法设计与应用基础
- 算法设计与应用基础
- 算法设计与应用基础
- 算法设计与应用基础
- 算法设计与应用基础
- ES6--promise
- 我的学习之路_第六章_跌打器,泛型
- 离散题目3(判断是否为子集)
- linux驱动调试之自制工具—寄存器编辑器
- 算法设计与应用基础
- libcurl with zlib 动态库 在 VS 下的编译
- 使用文献管理软件Mendeley插入参考文献和引用
- USACO之milk3
- 37 WebGL多个模型组成一个复杂的模型
- C++ 02 —— 访问权限
- SpringMVC的拦截器(Interceptor)和过滤器(Filter)的区别与联系
- 一个创建工程目录的shell脚本
- linux驱动调试之段错误分析_根据pc值确定出错的代码位置