Complete the code to find the maximum profit from a single buy-sell transaction.
fn max_profit(prices: Vec<i32>) -> i32 {
let mut min_price = i32::MAX;
let mut max_profit = 0;
for price in prices {
if price < [1] {
min_price = price;
} else if price - min_price > max_profit {
max_profit = price - min_price;
}
}
max_profit
}The variable min_price keeps track of the lowest price seen so far to calculate profit correctly.
Complete the code to calculate maximum profit with unlimited transactions.
fn max_profit_unlimited(prices: Vec<i32>) -> i32 {
let mut profit = 0;
for i in 1..prices.len() {
if prices[i] > prices[[1]] {
profit += prices[i] - prices[i - 1];
}
}
profit
}We compare the current price with the previous day's price to add profit for every increase.
Fix the error in the code to calculate max profit with at most two transactions.
fn max_profit_two_transactions(prices: Vec<i32>) -> i32 {
let n = prices.len();
if n == 0 {
return 0;
}
let mut left_profits = vec![0; n];
let mut right_profits = vec![0; n + 1];
let mut min_price = prices[0];
for i in 1..n {
min_price = min_price.min(prices[i]);
left_profits[i] = left_profits[i - 1].max(prices[i] - min_price);
}
let mut max_price = prices[n - 1];
for i in (0..n).rev() {
max_price = max_price.max(prices[i]);
right_profits[i] = right_profits[i + 1].max(max_price - prices[[1]]);
}
let mut max_profit = 0;
for i in 0..n {
max_profit = max_profit.max(left_profits[i] + right_profits[i + 1]);
}
max_profit
}i + 1 causing out-of-bound accessi - 1 causing negative indexWe use prices[i] to calculate the profit from the right side correctly.
Fill both blanks to complete the code for max profit with cooldown period.
fn max_profit_with_cooldown(prices: Vec<i32>) -> i32 {
let n = prices.len();
if n <= 1 {
return 0;
}
let mut sell = vec![0; n];
let mut buy = vec![0; n];
buy[0] = -prices[0];
for i in 1..n {
buy[i] = buy[i - 1].max(sell[[1]] - prices[i]);
sell[i] = sell[i - 1].max(buy[i - 1] + prices[[2]]);
}
sell[n - 1]
}i - 1 for both buy and sell causing logic errorsi causing index out of boundsFor cooldown, buying depends on selling two days before (i - 2), and selling depends on buying the previous day (i - 1).
Fill all three blanks to complete the code for max profit with transaction fee.
fn max_profit_with_fee(prices: Vec<i32>, fee: i32) -> i32 {
let n = prices.len();
if n == 0 {
return 0;
}
let mut cash = 0;
let mut hold = -prices[0];
for i in 1..n {
cash = cash.max(hold + prices[[1]] - [2]);
hold = hold.max(cash - prices[[3]]);
}
cash
}We use the current day index i for prices, subtract the fee when selling, and update hold accordingly.
