Member-only story
Coding Interview Prep: Best Time to Buy and Sell Stock in JavaScript with Explanation
2 min readJul 15, 2024
Code Solution
var maxProfit = function(prices){
let left = 0;
let right = 1;
let maxProfit = 0;
for (let i=0; i<prices.length; i++){
if (prices[left] < prices[right]){
const profit = prices[right]-prices[left];
maxProfit = Math.max(maxProfit, profit);
} else if (right > left){
left = right;
}
right++;
}
return maxProfit;
}
Time Complexity: O(n)
Space Complexity: O(1)
Explanation
This is a question that uses the sliding window algorithm. This algorithm is a method used to efficiently solve problems that involve defining a window or range in the input data and the moving that window across the data to perform some operation within the window. This technique is commonly used in algorithms like finding subarrays with a specific sum, finding the longest substring with unique characters, or solving problems that require a fixed-size window to process elements efficiently. There are 2 types of sliding window techniques. First is…