← Greedy

Best Time Buy Sell Stock

Easy
Python
def max_profit(prices):
    mn,profit=float('inf'),0
    for p in prices:
        mn=min(mn,p); profit=max(profit,p-mn)
    return profit
Java
public int maxProfit(int[] prices){
    int mn=Integer.MAX_VALUE,profit=0;
    for(int p:prices){
        mn=Math.min(mn,p); profit=Math.max(profit,p-mn);
    } return profit;
}

Key Insight

Greedy. float('inf') vs Integer.MAX_VALUE.

Python → Java Differences

  • float('inf') vs Integer.MAX_VALUE
  • min/max vs Math.min/max
  • Greedy scan identical
Python
def max_profit(prices):
    mn,profit=float('inf'),0
    for p in prices:
        mn=min(mn,p); profit=max(profit,p-mn)
    return profit
Java
public int maxProfit(int[] prices){
    int mn=Integer.MAX_VALUE,profit=0;
    for(int p:prices){
        mn=Math.min(mn,p); profit=Math.max(profit,p-mn);
    } return profit;
}

Algorithm Steps

1. Track min price
2. Update max profit