LeetCode: Best Time to Buy and Sell Stock I、II、III
2014-09-05 17:09
567 查看
Title three:
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).
说明:求两个交易利润的最大值,其中在第一次交易完成前不能进行第二次交易,也就是第二次购买的时间值小于或等于第一次卖出的时间值。
将prices拆分为两部分,分别利用题一中的方法进行求两部分的最大利润值然后求和。时间复杂度为O(n^2)
或者先前向遍历求出一个个值之前的最大利润值,再后面遍历一个个值之后最大利润值,然后进行求和得到最大值。时间复杂度O(n)
pro1[i]:表示在0 --- i之前完成一次交易的最大利润
pro2[j]:表示在j --- size-1之后完成一次交易的最大利润值
程序:
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).
说明:求两个交易利润的最大值,其中在第一次交易完成前不能进行第二次交易,也就是第二次购买的时间值小于或等于第一次卖出的时间值。
将prices拆分为两部分,分别利用题一中的方法进行求两部分的最大利润值然后求和。时间复杂度为O(n^2)
或者先前向遍历求出一个个值之前的最大利润值,再后面遍历一个个值之后最大利润值,然后进行求和得到最大值。时间复杂度O(n)
pro1[i]:表示在0 --- i之前完成一次交易的最大利润
pro2[j]:表示在j --- size-1之后完成一次交易的最大利润值
程序:
class Solution { public: int maxProfit(vector<int> &prices) { int size=prices.size(); if(0==size) return 0; vector<int> pro1(size); vector<int> pro2(size); int minval=prices[0]; for(int i=1;i!=size;++i) { minval=std::min(minval,prices[i]); pro1[i]=std::max(pro1[i-1],prices[i]-minval); } int maxval=prices[size-1]; for(int j=size-2;j>0;--j) { maxval=std::max(maxval,prices[j]); pro2[j]=std::max(pro2[j+1],maxval-prices[j]); } int sum=0; for(int i=0;i!=size;++i) { sum=std::max(sum,pro1[i]+pro2[i]); } return sum; } };
相关文章推荐
- Best Time to Buy and Sell Stock I,II,III [leetcode]
- [Leetcode][JAVA] Best Time to Buy and Sell Stock I, II, III
- LeetCode之“动态规划”:Best Time to Buy and Sell Stock I && II && III && IV
- LeetCode Best Time to Buy and Sell Stock I II III
- Leetcode: Best Time to Buy and Sell Stock I II III
- LeetCode - Best Time to Buy and Sell Stock I && II && III && IV
- 【leetcode】Best Time to Buy and Sell Stock I&II&III
- LeetCode: Best Time to Buy and Sell Stock I && II && III
- 【LeetCode】 Best Time to Buy and Sell Stock I II III IV 解题报告
- leetcode day6 -- String to Integer (atoi) && Best Time to Buy and Sell Stock I II III
- 【LeetCode】Best Time to Buy and Sell Stock I && II && III
- [leetcode]Best Time to Buy and Sell Stock I, II, III
- 【LeetCode】 Best Time to Buy and Sell Stock I II III IV 解题报告
- 【leetcode】Array——Best Time to Buy and Sell Stock I/II/III
- LeetCode Best Time to Buy and Sell Stock I,II,III
- leetcode Best Time to Buy and Sell Stock I&&II&&III
- LeetCode-Best Time to Buy and Sell Stock I II III IV
- LeetCode OJ Best Time to Buy and Sell Stock I II III IV
- leetcode(121)(122)(123)(188) Best Time to Buy and Sell Stock I/II/III/IV JAVA代码
- [Leetcode] Best Time to Buy and Sell Stock I,II,III,IV