题目:
ay 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).
解析:
只能买卖两次,分别搞两个数组
动态规划
使用两个数组,forw和back。
forw[i]表示从0到i的最优买卖值(低买高卖,为正)。需要一次从左往右遍历。
back[i]表示从m-1到i的最差买卖值(高买低卖,为负)。需要一次从右往左遍历。
再对应元素相减:forw[i]-back[i]的最大值即解。
class Solution { public: int maxProfit(vector<int> &prices) { int m = prices.size(); if(m == 0) return 0; int ret = 0; vector<int> forw(m, 0); vector<int> back(m, 0); //forward int curMin = prices[0]; for(int i = 1; i < m; i ++) { curMin = min(curMin, prices[i]); forw[i] = max(forw[i-1], prices[i]-curMin); } //backward int curMax = prices[m-1]; for(int i = m-2; i >= 0; i --) { curMax = max(curMax, prices[i]); back[i] = min(back[i+1], prices[i]-curMax); ret = max(ret, forw[i]-back[i]); } return ret; } };