Leetcode notes: Best Time to Buy and Stock III
I. Description
Say you have an array for which the I-th 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 wait the stock before you buy again ).
Ii. Question Analysis
Compared with the previous two questions, this question limits the number of stock transactions and can only be traded twice at most.
You can use dynamic planning to complete the process. The first step is to scan and calculate the sequence.[0, …, i]Maximum profit inprofit, Using an arrayf1Save, the time complexity of this step isO(n).
Step 2: reverse scanning to calculate subsequences[i, …, n - 1]Maximum profit inprofit, Using an arrayf2Save, the time complexity of this step is alsoO(n).
The last step,f1 + f2To find the maximum value.
Iii. Sample Code
#include
#include
using namespace std;class Solution {public: int maxProfit(vector
&prices) { int size = prices.size(); if (size <= 1) return 0; vector
f1(size); vector
f2(size); int minV = prices[0]; for (int i = 1; i < size; ++i) { minV = std::min(minV, prices[i]); f1[i] = std::max(f1[i - 1], prices[i] - minV); } int maxV = prices[size - 1]; f2[size - 1] = 0; for (int i = size-2; i >= 0; --i) { maxV = std::max(maxV, prices[i]); f2[i] = std::max(f2[i + 1], maxV - prices[i]); } int sum = 0; for (int i = 0; i < size; ++i) sum = std::max(sum, f1[i] + f2[i]); return sum; }};
Iv. Summary
Compared with the first two questions, this question is more difficult, and there are several questions related to this question. Subsequent Updates...