Problems178
Search for a command to run...
One transaction · track min price, maximize sell−buy profit
Try your own input
Change the array and replay the algorithm from step one.
Initialize tracking values
Find the maximum profit from a single buy and sell. Track minimum price seen so far.
One Pass
1function maxProfit(prices) {//minPrice: ∞maxProfit: 0day: —2 let minPrice = Infinity;3 let maxProfit = 0;4 for (let i = 0; i < prices.length; i++) {5 if (prices[i] < minPrice) {6 minPrice = prices[i];7 } else if (prices[i] - minPrice > maxProfit) {8 maxProfit = prices[i] - minPrice;9 }10 }11 return maxProfit;12}