LeetCode题解-Best Time to Buy and Sell Stock III
来源:互联网 发布:laravel mac 环境 编辑:程序博客网 时间:2024/05/23 17:55
在Best Time to Buy and Sell Stock II基础上增加条件:两次交易的最大收益
思路一:将数组分为前后两部分,数组大小为size,记分隔符为i,分别求(0,i)以及(i+1,size-1)的最大收益(很一般的思路,没有过大数据关,主要是有太多重复计算),将收益相加,即为本次的最大值,依次迭代,即可获得最大收益。
思路二:分别计算正向收益(见Best Time to Buy and Sell Stock)以及逆向收益,将相应收益相加,找最大收益。
代码1:
int Profit(vector<int>& prices,const int& start,const int& end){int minPrice=INT_MAX;int maxProfit=0;for (int i=start;i<=end;i++){minPrice=min(prices[i],minPrice);int diff=prices[i]-minPrice;if(diff>maxProfit)maxProfit=diff;}return maxProfit;}int maxProfit(vector<int>& prices){int size=prices.size();if(size<=1)return 0;int sum=0;int max1,max2=0;for (int i=0;i<size;i++){max1=Profit(prices,0,i);max2=Profit(prices,i+1,size-1);sum=max(max1+max2,sum);}return sum;}代码2:
<span style="font-family:KaiTi_GB2312;font-size:18px;">int Profit(vector<int> &prices) { int size=prices.size(); if(size <= 1) return 0; vector<int> maxFromLeft(prices.size(), 0); vector<int> maxFromRight(prices.size(), 0); int minPrice=INT_MAX;int maxProfit=INT_MIN; for(int i =0; i< size; i++) { minPrice=min(prices[i],minPrice);maxProfit=max(maxProfit,prices[i]-minPrice); maxFromLeft[i] = maxProfit; } int maxPrice=INT_MIN;maxProfit=INT_MIN; for(int i =size-1; i>=0; i--) { maxPrice=max(prices[i],maxPrice); maxProfit=max(maxProfit,maxPrice-prices[i]); maxFromRight[i] = maxProfit; } maxProfit = INT_MIN; for(int i =0; i< size-1; i++) { int sum = maxFromLeft[i] + maxFromRight[i+1];maxProfit=max(sum,maxProfit); } if(maxProfit < maxFromRight[0]) maxProfit = maxFromRight[0]; return maxProfit; } </span>
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 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
- PHP:快速排序法
- 欢迎使用CSDN-markdown编辑器
- java面向对象的思想
- swing 将system.out输出的信息重定向到JTEXTAREA
- 进程状态
- LeetCode题解-Best Time to Buy and Sell Stock III
- 认识shell
- 每天一个linux命令(1):ls命令
- 一种新的Activity转换动画实现方式
- 四种支持向量机工具箱使用概念
- CSAPP LAB---MALLOC实验
- Java8对《编程导论(Java)》的影响
- ActionBar 设置图片、Home返回、Background图片
- 前序遍历和中序遍历树构造二叉树