Top Interview 150
Maximizing profit from stock prices is a classic problem that teaches you how to analyze and optimize data with minimal computation. Let's dive into LeetCode 121: Best Time to Buy and Sell Stock and explore a clean, efficient solution in JavaScript.
π Problem Description
Given an array prices
, where prices[i]
is the price of a stock on the ith
day, find the maximum profit you can achieve from a single transaction (buy one day, sell on another day).
Note: You must buy before you sell.
If no profit is possible, return 0
.
π‘ Examples
Example 1
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6). Profit = 6 - 1 = 5.
Example 2
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: No profit can be made as prices decrease every day.
π JavaScript Solution
To solve this problem efficiently, we'll use a single pass approach, keeping track of the minimum price and maximum profit as we iterate through the array.
Optimized Solution
var maxProfit = function(prices) {
let minPrice = Infinity;
let maxProfit = 0;
for (let price of prices) {
minPrice = Math.min(minPrice, price);
maxProfit = Math.max(maxProfit, price - minPrice);
}
return maxProfit;
};
π How It Works
- Track the Minimum Price:
- As you iterate, keep track of the smallest price encountered so far.
- Calculate Potential Profit:
- For each price, calculate the profit as the difference between the current price and the minimum price.
- Update Maximum Profit:
- Compare the calculated profit with the current maximum profit and update it if higher.
π Complexity Analysis
- > Time Complexity:
O(n)
, where n is the number of days. The array is traversed once. - > Space Complexity:
O(1)
, as we only use two variables: minPrice and maxProfit.
π Dry Run
Input: prices = [7,1,5,3,6,4]
Output: 5
β¨ Pro Tips for Interviews
- Clarify assumptions: Ensure the interviewer confirms thereβs always at least one price in the input.
- Handle edge cases:
Single-day input
(prices.length = 1)
. Constant or decreasing prices([7,6,5,4,3])
. - Explain your thought process: Highlight how tracking the minimum price optimizes the solution.
π Learn More
Check out the detailed explanation and code walkthrough on my Dev.to post:
π Rotate Array - JavaScript Solution
How would you approach this problem? Let me know your thoughts! π
Top comments (0)