Best Time to Buy and Sell Stock III - Hard - L - Star
Published:
Question
- https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/
You are given an array prices where prices[i] is the price of a given stock on the ith day.
Find the maximum profit you can achieve. You may complete at most two transactions.
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Approach
- Variable iteration
- https://medium.com/algorithms-and-leetcode/best-time-to-buy-sell-stocks-on-leetcode-the-ultimate-guide-ce420259b323
Solution
class Solution {
public:
int maxProfit(vector<int>& prices) {
int a,b,c,d;
a = INT_MIN;
b = 0;
c = INT_MIN;
d = 0;
int n = prices.size();
for(int i=0; i<n; i++) {
a = max(a, -prices[i]);
b = max(b, a+prices[i]);
c = max(c, b-prices[i]);
d = max(d, c+prices[i]);
}
return d;
}
};