123. Best Time to Buy and Sell Stock III ~~
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).
这道题要求我们最多做两笔交易,求其最大利润。此题是DP题目,需要写出状态方程,即profit = transaction(1)+transaction(2)=sell(1)-buy(1)+sell(2)-buy(2)。代码如下:
public class Solution {
public int maxProfit(int[] prices) {
int buy1 = Integer.MIN_VALUE;
int buy2 = Integer.MIN_VALUE;
int sell1 = 0;
int sell2 = 0;
for(int i=0;i<prices.length;i++){
buy1 = Math.max(buy1,-prices[i]);
sell1 = Math.max(sell1,prices[i]+buy1);
buy2 = Math.max(buy2,sell1-prices[i]);
sell2 = Math.max(sell2,buy2+prices[i]);
}
return sell2;
}
}
最新文章
- Web前端温故知新-CSS基础
- C#如果把A.new()编译成new A()
- js常用函数
- Spring中Template模式与callback的结合使用浅析
- python 不得不知的第三方库以及常用安装包
- 160913、ionic + 高德地图定位
- 试写Python内建函数range()
- IIS7报错:如果要使用托管的处理程序,请安装 ASP.NET
- 解决linux ping: unknown host www.baidu.com(转)
- Angular JS 学习笔记(一)
- How to Create Dump File for Applications
- Windows下用Mingw编译Boost.Regex库
- Dynamics CRM 2013 体验
- js中子页面父页面方法和变量相互调用
- SQL AlawaysOn 之三:SQL服务器加入域
- python机器学习实战(四)
- Linux学习之CentOS(十八)-----恢复Ext3下被删除的文件与 使用grep恢复被删文件内容(转)
- vue部署的路径问题
- React动画组件——React-Transitio-group动画实现
- 关于 Nginx 配置 WebSocket 400 问题
热门文章
- JavaScript 在线测试
- PHP一句话后门过狗姿势万千之传输层加工
- emacs - GNU Emacs
- java GZIP压缩与解压缩
- Redux 和 mobx的区别
- Mysql 访问远程数据库,报错:1130-host ... is not allowed to connect to this MySql server 开放mysql远程连接 不使用localhost
- Hydraulic Motor Manufacturers - What Is A Cycloidal Hydraulic Motor?
- TWaver可视化编辑器的前世今生(三)Doodle编辑器
- Shell替换数组元素之间的间隔符号
- 离散数学-集合的交并差集运算--STL-set类