Leetcode74: Best Time to Buy and Sell Stock III
2015-09-22 14:40
447 查看
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 two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
只能允许两次买卖,可以用动态规划的思想,第一步扫描,先计算出子序列[0,...,i]中的最大利润,用一个数组保存下来,那么时间是O(n)。第二步是逆向扫描,计算子序列[i,...,n-1]上的最大利润,这一步同时就能结合上一步的结果计算最终的最大利润了,这一步也是O(n)。 所以最后算法的复杂度就是O(n)的。
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
只能允许两次买卖,可以用动态规划的思想,第一步扫描,先计算出子序列[0,...,i]中的最大利润,用一个数组保存下来,那么时间是O(n)。第二步是逆向扫描,计算子序列[i,...,n-1]上的最大利润,这一步同时就能结合上一步的结果计算最终的最大利润了,这一步也是O(n)。 所以最后算法的复杂度就是O(n)的。
class Solution { public: int maxProfit(vector<int>& prices) { int size = prices.size(); if(size == 0) return 0; int *cost1 = new int[size]; cost1[0] = 0; int min = prices[0]; int res = 0; for(int i = 1; i < size; i++) { if(prices[i] < min) min = prices[i]; if(prices[i] - min > res) res = prices[i] - min; cost1[i] = res; } int *cost2 = new int[size]; cost2[size-1] = 0; int max = prices[size-1]; res = 0; for(int i = size-2; i >= 0; i--) { if(prices[i] > max) max = prices[i]; if(max - prices[i] > res) res = max - prices[i]; cost2[i] = res; } int result = cost1[0]+cost2[0]; for(int i = 0; i < size; i++) { if(cost1[i]+cost2[i] > result) result = cost1[i]+cost2[i]; } return result; } };
相关文章推荐
- js 限制只能输入数字和一个小数,且第一位不能为小数
- <转>主流蓝牙BLE控制芯片详解(4):Nordic nRF51822
- linux常用命令(46):telnet 命令
- struts配置中,页面跳转
- proxy-target-class="true" 与proxy-target-class="false"的区别
- JAVA导出Excel(支持多sheet)
- 使用phpstorm来进行svn提交
- elasticsearch csv plugin
- Ueditor结合七牛云及百度云存储(JAVA版,ueditor-1.4.3)实现图片文件上传
- Spring Data Jpa 详解
- MongoDB运行状态、性能监控,分析
- 修练8年C++面向对象程序设计之体会
- svn下本地工程在服务器上的url以及信息
- 怎么快速 把一个 监听事件 变成 一个 内部类 在编程一个新的 java文件
- 数据库把一项设置成为不能重复的
- RHEL7 CENTOS7
- VS2010中汉字拷贝到Word出现乱码问题解决
- Java 二分查找的简单使用
- 利用PHP fsockopen 模拟POST/GET传送数据的方法
- Netfilter原理