LeetCode_Best Time to Buy and Sell Stock III
2013-04-11 23:31
393 查看
class Solution { public: int maxProfit(vector<int> &prices) { // Start typing your C/C++ solution below // DO NOT write int main() function if(prices.size() <2) return 0; int *profit = new int[prices.size()]; memset(profit,0, sizeof(int)*prices.size()) ; int i,min,maxProfit = 0,maxValue; min = prices[0] ; for(i =1; i< prices.size();i++) { if(prices[i] >= min ) { maxProfit = max(maxProfit,prices[i]- min ) ; profit[i] = maxProfit ; }else { profit[i] = maxProfit ; min = prices[i]; } } i--; maxValue= prices[i] ; maxProfit = 0; for( i--; i>= 0;i--) { if(prices[i] < maxValue ) { maxProfit = max(maxProfit,maxValue - prices[i] ); profit[i] += maxProfit ; }else { profit[i] += maxProfit ; maxValue = prices[i]; } } maxProfit = profit[0]; for(i=1;i<prices.size();i++) if(profit[i] > maxProfit) maxProfit = profit[i] ; delete []profit ; return maxProfit; } };
分析: 这道题主要是求一个分界点,分界点左侧的最大收益和右侧的最大收益之和最大,当然也可能只进行了一次交易。所以上面两边遍历,第一遍遍历求得是分界点左侧的最大收益,第二遍求得是分界点右侧的最大收益。
相关文章推荐
- Leetcode 123. Best Time to Buy and Sell Stock III 股票买卖3 解题报告
- [leetcode 123] Best Time to Buy and Sell Stock III
- [Leetcode]Best Time to Buy and Sell Stock III
- [LeetCode] Algorithms-45. 123. Best Time to Buy and Sell Stock III
- [LeetCode] [Python] [DP] Best Time to Buy and Sell Stock III
- 111_leetcode_Best Time to Buy and Sell Stock III
- LeetCode | Best Time to Buy and Sell Stock III
- [LeetCode 123] - 买入与卖出股票的最佳时机III(Best Time to Buy and Sell Stock III)
- [leetcode]Best Time to Buy and Sell Stock III @ Python
- [leetcode]Best Time to Buy and Sell Stock III
- LeetCode(123) Best Time to Buy and Sell Stock III (Java)
- [Leetcode] #121#122#123#188 Best Time to Buy and Sell Stock I & II & III & IV
- [LeetCode] Best Time to Buy and Sell Stock III
- LeetCode123: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]题解(python):123-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第28题(best-time-to-buy-and-sell-stock-iii)