LeetCode Best Time to Buy and Sell Stock III
来源:互联网 发布:oracle数据库迁移 编辑:程序博客网 时间:2024/06/07 05:27
题目
Say you have an array for which the ith element is the price of a given stock on dayi.
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).
紧接着前面两题,这次可以买两份,但是不能同时持有。
也就是说两次购买分布在两段区间上,不重合。
所以:
1、以某个位置作为划分,在前后两段区间上各操作一次买卖,获得两个区间上各自的最大利润,即为相应划分的最大利润。
2、对所有划分获得的各自的最大利润取最大即可获得全局的最大利润。
这样的操作看起来是n^2的,但是,连续的不同划分只是通过改变了前后区间的最高和最低价格,从而对最终利润产生影响。
所以可以可以通过dp实现O(n)的求解。
保留从0到i位置的最大利润profit_forward、从i到最后位置的最大利润profit_backward。递推公式如下:
1、profit_forward[i+1]=max(profit_forward[i],prices[i+1]-min),刷新min;
2、profit_backward[i-1]=max(profit_backward[i],max-prices[i-1]),刷新max;
即可实现O(n)求解。
代码:
class Solution {public: int maxProfit(vector<int> &prices) { if(prices.empty())return 0;vector<int> profit_forward(prices.size(),0),profit_backward(prices.size(),0);//到当前位置可以获得的最大利润,当前位置到尾可以获得的最大利润int min=prices[0],max=prices[prices.size()-1],profit=0;//目前的最低价格,最高价格,最大利润for(int i=1;i<prices.size();i++)//正向扫描{profit_forward[i]=prices[i]-min>profit_forward[i-1]?prices[i]-min:profit_forward[i-1];min=prices[i]<min?prices[i]:min;}for(int i=prices.size()-2;i>=0;i--)//反向扫描{profit_backward[i]=max-prices[i]>profit_backward[i+1]?max-prices[i]:profit_backward[i+1];max=prices[i]>max?prices[i]:max;}for(int i=0;i<prices.size();i++)//合并返回最高利润profit=profit_forward[i]+profit_backward[i]>profit?profit_forward[i]+profit_backward[i]:profit;return profit; }};
- 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
- [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
- 【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]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]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-Best Time to Buy and Sell Stock III
- FFT
- asp.net文章截取摘要用省略号表示
- tomcat性能调优
- 基于MySQL到MongoDB简易对照表的详解
- win8.1 android studio安装Genymotion集成virtualbox,出现严重错误
- LeetCode Best Time to Buy and Sell Stock III
- PowerDesigner15.1使用技巧
- Top 10 Websites to Learn Coding (Interactively) Online
- 信息安全意识如何免费宣贯
- 南工No.88 汉诺塔(一)
- webx相关概念与具体处理流程
- 开始刷leetcode day5:Reverse Integer
- vs2012编译libcurl-7.38.0
- leetcode 日经贴,Cpp code -Permutations