LeetCode —— Best Time to Buy and Sell Stock III
2013-08-06 19:43
435 查看
链接:http://leetcode.com/onlinejudge#question_123
原题:
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).
思路:简单的动态规划,因为限定最多只能有两次交易,而且交易不能重叠。那么分两步走好了,
由左向右记录一下到那一天为止最大的收益;同样,由右到左,记录最大收益。
然后加一加就可以了。
代码:
原题:
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).
思路:简单的动态规划,因为限定最多只能有两次交易,而且交易不能重叠。那么分两步走好了,
由左向右记录一下到那一天为止最大的收益;同样,由右到左,记录最大收益。
然后加一加就可以了。
代码:
class Solution { public: int maxProfit(vector<int> &prices) { // Start typing your C/C++ solution below // DO NOT write int main() function int size = prices.size(); if (size <= 1) return 0; vector<int> leftIncomes(size, 0); vector<int> rightIncomes(size, 0); int min = prices[0]; for (int i=1; i<size; i++) { if (prices[i] < min) min = prices[i]; if (prices[i] - min > leftIncomes[i-1]) leftIncomes[i] = prices[i] - min; else leftIncomes[i] = leftIncomes[i-1]; } int max = prices.back(); for (int i=size-2; i>=0; i--) { if (prices[i] > max) max = prices[i]; if (max - prices[i] > rightIncomes[i+1]) rightIncomes[i] = max - prices[i]; else rightIncomes[i] = rightIncomes[i+1]; } int profit = 0; for (int i=0; i<size; i++) { if (leftIncomes[i] + rightIncomes[i] > profit) profit = leftIncomes[i] + rightIncomes[i]; } 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 I II III
- leetcode - Best Time to Buy and Sell Stock III
- 4 Best Time to Buy and Sell Stock III_Leetcode
- [LeetCode] Best Time to Buy and Sell Stock I II III IV
- 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(dp)
- [LeetCode]Best Time to Buy and Sell Stock III
- LeetCode_Best Time to Buy and Sell Stock III
- [leetcode-123]Best Time to Buy and Sell Stock III(c++)
- Leetcode::Best Time to Buy and Sell Stock III
- leetcode解题报告: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_best-time-to-buy-and-sell-stock-iii
- LeetCode: Best Time to Buy and Sell Stock III
- LeetCode – Refresh – Best Time to Buy and Sell Stock iii
- LeetCode 123 Best Time to Buy and Sell Stock III