123. Best Time to Buy and Sell Stock III
来源:互联网 发布:mysql 重启服务 编辑:程序博客网 时间:2024/06/08 16:25
问题描述
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).解决思路
和第121题一样的,只是变成了两次操作而已。用两个buy变量和两个sell变量实现动态规划即可。(注意,第二次buy的状态转移方程为buy2 = max(buy2,-prices[i]+sell1))代码
class Solution {public: int maxProfit(vector<int>& prices) { if (prices.size() == 0) return 0; int buy1 = INT_MIN ,sell1 = INT_MIN , buy2 = INT_MIN, sell2 = INT_MIN; for (int i = 0 ; i < prices.size(); ++i) { buy1 = max(buy1,-prices[i]); sell1 = max(sell1,prices[i]+buy1); buy2 = max(buy2,sell1-prices[i]); sell2 = max(sell2,buy2+prices[i]); } return sell2; }};
0 0
- LeetCode 123. Best Time to Buy and Sell Stock III
- 123.Best Time to Buy and Sell Stock III
- [Leetcode]123.Best Time to Buy and Sell Stock III
- [Leetcode] 123. Best Time to Buy and Sell Stock III
- 123. Best Time to Buy and Sell Stock III
- [leetcode] 123.Best Time to Buy and Sell Stock III
- 【leetcode】123. Best Time to Buy and Sell Stock III
- 123. Best Time to Buy and Sell Stock III
- [leetcode] 123. Best Time to Buy and Sell Stock III
- 123. Best Time to Buy and Sell Stock III
- 123. Best Time to Buy and Sell Stock III
- leetcode 123. Best Time to Buy and Sell Stock III
- leetcode 123. Best Time to Buy and Sell Stock III
- 123. Best Time to Buy and Sell Stock III
- 123. Best Time to Buy and Sell Stock III
- [LeetCode] 123. Best Time to Buy and Sell Stock III
- 123. Best Time to Buy and Sell Stock III
- Leetcode 123. Best Time to Buy and Sell Stock III
- 数字限时增长效果实现:numberGrow.js------遇到的产品提的要求
- 欢迎使用CSDN-markdown编辑器
- 使用清华tuna下载anaconda安装ipython notebook
- nginx源码学习(二)
- C语言 字符串截取
- 123. Best Time to Buy and Sell Stock III
- hdu 1839 Delay Constrained Maximum Capacity Path 二分+最短路
- 关于java中AWT和Swing之间的区别鱼联系?
- Ansible 系列之 Ad-Hoc介绍及使用
- Django中关于根据配置生成SQL语句的问题
- Python 异常处理 try/except
- MyBatis 官方文档学习2---XML 映射配置文件
- 蓝桥杯 —— 石子合并问题 —— Dp
- R语言 读取文件,一行一行处理, 写入文件