#122
Medium Algorithms Best time to buy and sell stock ii
Array Dynamic Programming Greedy
70.8% acceptance
Jan 12, 2026
15287
2814
You are given an integer array prices where prices[i] is the price of a given stock on the ith day.
On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can sell and buy the stock multiple times on the same day, ensuring you never hold more than one share of the stock.
Find and return the maximum profit you can achieve.
Solution
Rust
Time O(2^n)
Space O(n)
impl Solution {
pub fn max_profit_ii(prices: Vec<i32>) -> i32 {
Self::max_profit(prices)
}
fn max_profit(prices: Vec<i32>) -> i32 {
let mut profit = 0;
for i in 1..prices.len() {
if prices[i] > prices[i - 1] {
profit += prices[i] - prices[i - 1];
}
}
profit
}
}