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;

}

}

最新文章

  1. Web前端温故知新-CSS基础
  2. C#如果把A.new()编译成new A()
  3. js常用函数
  4. Spring中Template模式与callback的结合使用浅析
  5. python 不得不知的第三方库以及常用安装包
  6. 160913、ionic + 高德地图定位
  7. 试写Python内建函数range()
  8. IIS7报错:如果要使用托管的处理程序,请安装 ASP.NET
  9. 解决linux ping: unknown host www.baidu.com(转)
  10. Angular JS 学习笔记(一)
  11. How to Create Dump File for Applications
  12. Windows下用Mingw编译Boost.Regex库
  13. Dynamics CRM 2013 体验
  14. js中子页面父页面方法和变量相互调用
  15. SQL AlawaysOn 之三:SQL服务器加入域
  16. python机器学习实战(四)
  17. Linux学习之CentOS(十八)-----恢复Ext3下被删除的文件与 使用grep恢复被删文件内容(转)
  18. vue部署的路径问题
  19. React动画组件——React-Transitio-group动画实现
  20. 关于 Nginx 配置 WebSocket 400 问题

热门文章

  1. JavaScript 在线测试
  2. PHP一句话后门过狗姿势万千之传输层加工
  3. emacs - GNU Emacs
  4. java GZIP压缩与解压缩
  5. Redux 和 mobx的区别
  6. Mysql 访问远程数据库,报错:1130-host ... is not allowed to connect to this MySql server 开放mysql远程连接 不使用localhost
  7. Hydraulic Motor Manufacturers - What Is A Cycloidal Hydraulic Motor?
  8. TWaver可视化编辑器的前世今生(三)Doodle编辑器
  9. Shell替换数组元素之间的间隔符号
  10. 离散数学-集合的交并差集运算--STL-set类