Best Time to Buy and Sell Stock

easy array greedy

Problem

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.

Inputprices = [8, 3, 6, 4, 9, 5]
Output6
Buy on day 1 at price 3, sell on day 4 at price 9. Profit = 9 − 3 = 6.

def best_profit(prices):
    min_so_far = float("inf")
    best = 0
    for p in prices:
        if p < min_so_far:
            min_so_far = p
        if p - min_so_far > best:
            best = p - min_so_far
    return best
function bestProfit(prices) {
  let minSoFar = Infinity;
  let best = 0;
  for (let i = 0; i < prices.length; i++) {
    if (prices[i] < minSoFar) minSoFar = prices[i];
    const profit = prices[i] - minSoFar;
    if (profit > best) best = profit;
  }
  return best;
}
class Solution {
    public int bestProfit(int[] prices) {
        int minSoFar = Integer.MAX_VALUE;
        int best = 0;
        for (int p : prices) {
            if (p < minSoFar) minSoFar = p;
            if (p - minSoFar > best) best = p - minSoFar;
        }
        return best;
    }
}
int bestProfit(vector<int>& prices) {
    int minSoFar = INT_MAX, best = 0;
    for (int p : prices) {
        if (p < minSoFar) minSoFar = p;
        if (p - minSoFar > best) best = p - minSoFar;
    }
    return best;
}
Time: O(n) Space: O(1)