LeetCode OJ 123 Best Time to Buy and Sell Stock III
来源:互联网 发布:qq采集软件 编辑:程序博客网 时间:2024/06/14 08:41
题目:
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).
难度:hard
思路:正向扫面在i处左边可得的最大利润,逆向扫面在i处右边可得的最大利润,再将所得的两个数组相加求最大值
代码如下
class Solution {public: int maxProfit(vector<int>& prices) { vector<int> profit1(prices.size(),0); vector<int> profit2(prices.size(),0); if(prices.size()<=1) return 0; int minPrice=prices[0]; for(int i=1;i<prices.size();i++){ minPrice= min(minPrice,prices[i]); profit1[i]=max(prices[i]-minPrice,profit1[i-1]); } int maxPrice=prices[prices.size()-1]; for(int i=prices.size()-2;i>=0;i--){ maxPrice = max(maxPrice,prices[i]); profit2[i]=max(maxPrice-prices[i],profit2[i+1]); } int maxProfit=0; for(int i=0;i<prices.size();i++){ maxProfit=max(maxProfit,profit1[i]+profit2[i]); } return maxProfit; }};
0 0
- LeetCode OJ:Best Time to Buy and Sell Stock III
- LeetCode OJ - 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 [123]
- LeetCode 123 Best Time to Buy and Sell Stock III
- [leetcode 123] Best Time to Buy and Sell Stock III
- leetcode || 123、Best Time to Buy and Sell Stock III
- leetcode-123 Best Time to Buy and Sell Stock III
- leetcode 123: Best Time to Buy and Sell Stock III
- 123 Best Time to Buy and Sell Stock III [Leetcode]
- Best Time to Buy and Sell Stock III - LeetCode 123
- LeetCode 123: Best Time to Buy and Sell Stock III
- LeetCode 123 Best Time to Buy and Sell Stock III
- LeetCode 123 -- Best Time to Buy and Sell Stock III
- Leetcode 123 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 123
- [Leetcode 123] Best Time to Buy and Sell Stock III
- Swift基础篇——函数
- 不改源码的方式实现osgearth当中placenode的中文支持
- 每天学点儿树莓派(三)——使用IDE提高效率
- Swift基础篇——构造函数
- Swift基础篇——setter和getter的使用
- LeetCode OJ 123 Best Time to Buy and Sell Stock III
- Swift基础篇——闭包
- Unity中HideInInspector和SerializeField
- Swift基础篇——懒加载
- Eclipse 常用快捷键
- Swift基础篇——单例
- Ember.js 入门指南——查询记录
- Swift基础篇——结构体
- POJ 1159 Palindrome