Skip to main content
Back to problems
#121
Easy Algorithms

Best time to buy and sell stock

Array Dynamic Programming
56.4% acceptance
Jan 12, 2026
35390
1410
You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

Solution

Rust
Time O(2^n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn max_profit_i(prices: Vec<i32>) -> i32 {
    Self::max_profit(prices)
  }
  
  fn max_profit(prices: Vec<i32>) -> i32 {
    let mut min_price = i32::MAX;
    let mut max_profit = 0;
    
    for price in prices {
      min_price = min_price.min(price);
      max_profit = max_profit.max(price - min_price);
    }
    
    max_profit
  }
}