Coding Interview Questions | Best Time to Buy and Sell Stock
December 14th, 2023
Introduction:
This summary will talk about my solution to the Best Time to Buy and Sell Stock problem
as seen on leetcode here.
Solution:
function maxProfit(prices: number[]): number {
let maxProfit = 0;
let minPrice = prices[0];
for (let dayIndex = 1; dayIndex < prices.length; dayIndex++) {
const currentDayPrice = prices[dayIndex];
const potentialMaxProfit = currentDayPrice - minPrice;
if (potentialMaxProfit > maxProfit) {
maxProfit = potentialMaxProfit;
}
if (currentDayPrice < minPrice) {
minPrice = currentDayPrice;
}
}
return maxProfit;
}
Summary:
The approach above iterates through the array of stock prices, maintaining two pointers: minPrice
and currentDayPrice
. It calculates the potential profit by subtracting minPrice
from the current day’s price and updates the maxProfit
if the potential profit is greater. The minPrice
is updated whenever a lower price is encountered. By adjusting these pointers only when needed, the algorithm identifies the maximum profit achievable by buying and selling the stock in one array loop, ensuring linear time complexity.