Best Time to Buy and Sell Stock III - LeetCode 123
来源:互联网 发布:珠海生活 知乎 编辑:程序博客网 时间:2024/05/16 09: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).
Hide Similar Problems
分析:
最多买卖两次,那就把元素组分成两段,分别求出两段的最大利益,然后相加,于是得到动态规划解法(类似于求出数组中除去自身元素外的其他所有元素的乘积):
先从前往后,求出第0天到第i天买卖一次能获得的最大利益,记入forward[i];
再从后往前,求出第i天到n-1 天买卖一次能获得的最大利益,记入backward[i];
然后两次买卖的最大利益 max_profi = max{forward[i] + backward[i]},其中i取值[0,n-1]
////////////////12ms//////////////////////////////////class Solution {public: /** * @param prices: Given an integer array * @return: Maximum profit */ int maxProfit(vector<int> &prices) { // write your code here int n = prices.size(); if(n < 2) return 0; if( n == 2) return prices[1]> prices[0]? prices[1] - prices[0]:0; vector<int> forward(n,0); //forward[i]表示从第0天到第i天买卖一次能获得的最大利益 vector<int> backward(n,0); //backward[i]表示从第i天到n-1天买卖一次能获得的最大利益 int min_p = prices[0]; for(int i = 1; i < n; i++){ //从前往后计算forward if(prices[i] < min_p) min_p = prices[i]; int t = prices[i] - min_p; forward[i] = max(t,forward[i-1]); } int max_p = prices[n-1]; for(int i = n-2; i >= 0; i--){ //从后往前计算backward if(prices[i] > max_p) max_p = prices[i]; int t = max_p - prices[i]; backward[i] = max(t,backward[i+1]); } int max_profi = 0; for(int i = 0; i < n - 1; i++){ //求出两段和最大值 int t = forward[i] + backward[i]; max_profi = max(max_profi , t); } return max_profi; }};
0 0
- 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
- **Leetcode 123 Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock III
- 暴雪公司关于字符串匹配的hash算法
- nginx无法启动: libpcre.so.1/libpcre.so.0: cannot open shared object file解决办法
- 静电边值问题的唯一性定理
- 字符串匹配算法之SimHash算法
- Html编码
- Best Time to Buy and Sell Stock III - LeetCode 123
- windows关闭端口
- 使用python操作solr
- 腾讯视频嵌入网页的方法
- Objective-C实现变参函数
- 【术】Unity中c#协程原理及实现
- debug工具
- javascript的$的操作
- Java 静态内部类 static class