Best Time to Buy and Sell Stock III
来源:互联网 发布:淘宝客服话术范文 编辑:程序博客网 时间:2024/05/22 09:05
题目没给例子,理解错题意了
用到了Best Time to Buy and Sell Stock I的动态规划方法,顺便复习一下
解题思路是:以第i天为分界线,计算第i天之前进行一次交易的最大收益preProfit[i],和第i天之后进行一次交易的最大收益postProfit[i],最后遍历一遍,max{preProfit[i] + postProfit[i]} (0≤i≤n-1)就是最大收益。
class Solution {public:int maxProfit(vector<int>& prices) {if (prices.size() < 2) return 0;int n = prices.size();vector<int> preProfit(n,0);vector<int> postProfit(n,0);int curMin = prices[0];for (int i = 1; i < n; i++) {curMin = min(curMin, prices[i]);preProfit[i] = max(preProfit[i - 1], prices[i] - curMin);}int curMax = prices[n - 1];for (int i = n - 2; i >= 0; i--) {curMax = max(curMax, prices[i]);postProfit[i] = max(postProfit[i + 1], curMax - prices[i]);}int maxProfit = 0;for (int i = 0; i < n; i++) {maxProfit = max(maxProfit, preProfit[i] + postProfit[i]);}return maxProfit;}};
0 0
- LeetCode Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock III
- [Leetcode] Best Time to Buy and Sell Stock III
- leetcode 16: Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock III
- [LeetCode] Best Time to Buy and Sell Stock III
- leetcode 62: Best Time to Buy and Sell Stock III
- [LeetCode] Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock III
- 【leetcode】Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock III
- LeetCode - Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock III
- LeetCode之Best Time to Buy and Sell Stock III
- [LeetCode]Best Time to Buy and Sell Stock III
- 购物图片放大镜
- 递归实现二叉树的三种遍历
- JavaScript 数组详解
- Eclipse—创建JavaWeb工程与Servlet
- android面试
- Best Time to Buy and Sell Stock III
- MVC一探究竟之Hibernate原理与实践
- struts常用配置
- mysql数据库的PDO连接方式
- 开启博客的新论点——建筑行业如何应用BIM的系列文章
- Oracle PL/SQL编程(1)
- 网络请求框架----HttpClient的get,post和图片上传服务器
- 数据库Sharding的基本思想和切分策略
- 下面关于ICMP协议的描述中,正确的是()----腾讯2016研发工程师笔试题