LeetCode —— Best Time to Buy and Sell Stock III
来源:互联网 发布:广富宝网络借贷 编辑:程序博客网 时间:2024/06/14 22:48
链接: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).
思路:简单的动态规划,因为限定最多只能有两次交易,而且交易不能重叠。那么分两步走好了,
由左向右记录一下到那一天为止最大的收益;同样,由右到左,记录最大收益。
然后加一加就可以了。
代码:
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; }};
- 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] 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
- 优化网站响应时间tomcat添加gzip
- Mini2440 DM9000 驱动分析(三)
- POJ 1142 A Walk Through the Forest ( 最短路 +记忆化搜索)
- Surrounded Regions
- eclipse最佳实践:快捷键
- LeetCode —— Best Time to Buy and Sell Stock III
- 2013 多校第五场 hdu 4648 Magic Pen 6
- IOS学习之路七(通过xib自定义UITableViewCell)
- android:background
- uva 565 Pizza Anyone?(二进制+搜索)
- hdu 2602 Bone Collector
- 什么是数据库分表技术
- strictmode
- HDU 4649 Professor Tian (2013多校联合5 1007)