Leetcode 贪心 Best Time to Buy and Sell Stock III
来源:互联网 发布:出国语言翻译软件 编辑:程序博客网 时间:2024/05/06 12:54
本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie
Best Time to Buy and Sell Stock III
Total Accepted: 8447 Total Submissions: 38417Say 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).
题意:给定一组数,表示某个股票每天的价格,问怎么买卖可获得最大利益。最多可以买卖再次
思路:分段动规
因为最多可买卖两次,所以可分将数组两段,每段取最大利益
设i将[1,n]分为[1,i]和[i,n](如果第一段在i卖,第二段在i买,则两段合为一段)
f[i]表示以i为结尾的最大利益
f[i] = max(f[i - 1], prices[i] - cur_min_price), cur_min_price表示当前最小价格
从0到n,求f[i]
g[i]表示以i为开头的最大利益
g[i] = max(g[i + 1], cur_max_price - prices[i]), cur_max_price表示当前最大价格
从n到n,求g[i]
因为最多可以买卖两次,即可以少于两次,所以允许在一天内既买又卖,即不交易。
这点体现在在求f[i],g[i]的时候,先求cur_min_price,cur_max_price,再求f[i],g[i],
最后的结果为
max{f(i) + g(i)}
复杂度:O(n)
class Solution {public: int maxProfit(vector<int> &prices){ int n = prices.size(); if(n < 2) return 0; vector<int> f(n, 0); vector<int> g(n, 0); for(int i = 1, cur_min_price = prices[0]; i < n; i++){ cur_min_price = min(cur_min_price, prices[i]); f[i] = max(f[i - 1], prices[i] - cur_min_price); } for(int j = n - 2, cur_max_price = prices[n - 1]; j > -1; j--){ cur_max_price = max(cur_max_price, prices[j]); g[j] = max(g[j + 1], cur_max_price - prices[j]); } int max_profit = 0; for(int i = 0; i < n; i++){ max_profit = max(max_profit, f[i] + g[i]); } return max_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 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
- JNI学习笔记——字符串操作
- 黑马程序员——集合
- linux--函数劫持--基于LD_PRELOAD
- Verilog HDL按键消抖
- Illegal attempt to associate a collection with two open sessions;
- Leetcode 贪心 Best Time to Buy and Sell Stock III
- JDBC的实现
- 黑马程序员 java基础24天 字符流
- 数据库连接-ADO.NET
- sourceInsight实用配置
- 软考历程(5)——extend 与 include
- C++ Primer 读书笔记(7)
- 3、Mac共享文件夹设置
- linux获取活动网卡ip地址