Best Time to Buy and Sell Stock III
来源:互联网 发布:linux killproc 编辑:程序博客网 时间:2024/05/16 15:39
题目: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).
思路:动态规划
思路就是分成两个数组preprofit和postprofit,分别表示从最开始到第i天的最大收益以及从第i天到最后一天的最大收益,第一个只需要判断最小值,判断一个profit,后面的是判断最大值,每次也要比较最大profit。
做这种题目的确有收获,难得的是第四道题目。
代码:
class Solution {public://http://liangjiabin.com/blog/2015/04/leetcode-best-time-to-buy-and-sell-stock.html//https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/ int maxProfit(vector<int>& prices) { if(prices.size()<2){ return 0; } int n=prices.size(); vector<int> preProfit(n,0); vector<int> postProfit(n,0); //从前往后 int minPrice=prices[0]; for(int i=1;i<=prices.size()-1;i++){ minPrice=min(minPrice,prices[i]); preProfit[i]=max(preProfit[i-1],prices[i]-minPrice); } //从后往前 int maxPrice=prices[n-1]; for(int i=n-2;i>=0;i--){ maxPrice=max(maxPrice,prices[i]); postProfit[i]=max(postProfit[i+1],maxPrice-prices[i]); } int maxProfit=0; for(int i=0;i<=preProfit.size()-1;i++){ maxProfit=max(maxProfit,postProfit[i]+preProfit[i]); } return maxProfit; }};
0 0
- 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
- Best Time to Buy and Sell Stock III
- 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
- Best Time to Buy and Sell Stock III
- 【leetcode】Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock III
- LeetCode - Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock III
- 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
- RecyclerView的通用适配器,和滚动时不加载图片的封装
- 大多数人并不知道的秘密:接地气,寿命长!
- ocp-311
- ocp-312
- ocp-313
- Best Time to Buy and Sell Stock III
- ocp-314
- ocp-315
- ocp-316
- ocp-317
- 僵尸国度.Z.Nation
- ocp-318
- ocp-319
- ocp-320