Complete the code to find the maximum profit from a single buy-sell transaction.
int maxProfit(vector<int>& prices) {
int minPrice = INT_MAX;
int maxProfit = 0;
for (int price : prices) {
minPrice = min(minPrice, [1]);
maxProfit = max(maxProfit, price - minPrice);
}
return maxProfit;
}We update the minimum price seen so far by comparing it with the current price.
Complete the code to calculate maximum profit with unlimited transactions.
int maxProfit(vector<int>& prices) {
int profit = 0;
for (int i = 1; i < prices.size(); i++) {
if (prices[i] [1] prices[i - 1]) {
profit += prices[i] - prices[i - 1];
}
}
return profit;
}We add profit only when today's price is greater than yesterday's price.
Fix the error in the code to calculate max profit with at most two transactions.
int maxProfit(vector<int>& prices) {
int n = prices.size();
if (n == 0) return 0;
vector<int> leftProfits(n, 0);
int minPrice = prices[0];
for (int i = 1; i < n; i++) {
minPrice = min(minPrice, prices[i]);
leftProfits[i] = max(leftProfits[i - 1], prices[i] - [1]);
}
vector<int> rightProfits(n + 1, 0);
int maxPrice = prices[n - 1];
for (int i = n - 2; i >= 0; i--) {
maxPrice = max(maxPrice, prices[i]);
rightProfits[i] = max(rightProfits[i + 1], maxPrice - prices[i]);
}
int maxProfit = 0;
for (int i = 0; i < n; i++) {
maxProfit = max(maxProfit, leftProfits[i] + rightProfits[i + 1]);
}
return maxProfit;
}We subtract the minimum price seen so far to calculate profit for the left side.
Fill both blanks to implement max profit with cooldown period after selling.
int maxProfit(vector<int>& prices) {
int n = prices.size();
if (n <= 1) return 0;
vector<int> sell(n, 0), buy(n, 0), cooldown(n, 0);
buy[0] = -prices[0];
for (int i = 1; i < n; i++) {
buy[i] = max(buy[i - 1], cooldown[i - 1] - [1]);
sell[i] = max(sell[i - 1], buy[i - 1] + prices[i]);
cooldown[i] = max(cooldown[i - 1], sell[i - 1]);
}
return max(sell[n - 1], cooldown[n - 1]);
}We buy by subtracting today's price from cooldown state, and cooldown is max of previous cooldown or sell.
Fill all three blanks to implement max profit with transaction fee.
int maxProfit(vector<int>& prices, int fee) {
int n = prices.size();
int cash = 0, hold = -prices[0];
for (int i = 1; i < n; i++) {
cash = max(cash, hold + prices[i] - [1]);
hold = max(hold, cash - [2]);
}
return cash;
}When selling, subtract the fee from the profit. When buying, subtract the current price.
