Best Time to Buy and Sell Stock
easy
Array
Challenge
You are given an integer array prices where prices[i] is the price of NeetCoin on the ith day. You want to maximize your profit by choosing a single day to buy one NeetCoin and choosing a different day in the future to sell that NeetCoin. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
<Code />
maxProfit(prices) {
let min = Infinity
let maxProfit = 0
for (let p of prices) {
if (p < min) {
min = p
} else if (p - min > maxProfit) {
maxProfit = p - min
}
}
return maxProfit
}
Thoughts
I really enjoy this problem because it feels very fair. You can reason about the question even if you've never seen this problem before, and the code is simple enough to write.