def max_profit(prices):
mn,profit=float('inf'),0
for p in prices:
mn=min(mn,p); profit=max(profit,p-mn)
return profit
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;
}
Greedy. float('inf') vs Integer.MAX_VALUE.
def max_profit(prices):
mn,profit=float('inf'),0
for p in prices:
mn=min(mn,p); profit=max(profit,p-mn)
return profit
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;
}
1. Track min price 2. Update max profit