Best Time to Buy and Sell Stock IV
2015-11-28 22:06
295 查看
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).
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).
class Solution { public: int maxProfit(int k, vector<int>& prices) { int n=prices.size(); if(k==0||n<2) return 0; if(k>n/2){ int res=0; for(int i=1;i<n;i++){ if(prices[i]-prices[i-1]>0){ res+=prices[i]-prices[i-1]; } } return res; } vector<int>buy(k,INT_MIN); vector<int>sell(k,0); for(int i=0;i<n;i++){ buy[0]=max(buy[0],-prices[i]); sell[0]=max(sell[0],buy[0]+prices[i]); for(int j=1;j<k;j++){ buy[j]=max(buy[j],sell[j-1]-prices[i]); sell[j]=max(sell[j],buy[j]+prices[i]); } } return sell[k-1]; } };
相关文章推荐
- 【简易通讯录】——C语言实现
- redhat6 在字符界面下安装图形界面。
- 数据结构——双向链表实现,基本操作的C++版
- 一个人花8块钱买了只鸡,9块钱卖了,又10块钱买回来,11块钱又卖了,他赚了多少钱?
- perl - 文件操作(一)
- Java中的基本数据类型转换
- KT学算法(四)——找数组中出现超过一半的数字的优雅解和拓展
- 读书笔记
- LVS Nginx HAProxy 优缺点
- 【FastDev4Android框架开发】实例解析之SwipeRefreshLayout+RecyclerView+CardView(三十五)
- 理解“统一编址与独立编址”,“I/O端口与I/O内
- 解决Android Studio更新错误
- Graphics
- CloudFoundry Nats实践
- android的定时任务
- AES —— JAVA中对称加密和解密
- 算法常用思想
- 【原】iOS动态性(四):一行代码实现iOS序列化与反序列化(runtime)
- Hadoop2.6.0学习笔记(七)HDFS读写流程
- 云计算、PaaS开发、企业云平台搭建