Welcome back to our LeetCode journey with TypeScript! In this post, we’re diving into a classic problem that frequently appears in technical interviews, especially at companies like Google and in hedge fund tech roles: Best Time to Buy and Sell Stock. This problem tests your ability to work with arrays and apply a greedy algorithm to maximize profit. Whether you’re preparing for a Silicon Valley interview or just sharpening your algorithmic skills, this problem offers valuable insights into efficient array traversal. Let’s break it down step by step, explore the concept with an ELI5 analogy, and implement a solution in TypeScript.
The problem is straightforward: you’re given an array of stock prices where each element represents the price of a stock on a particular day. Your goal is to maximize your profit by buying the stock on one day and selling it on a later day. If no profit is possible, you should return 0.
[7,1,5,3,6,4]
.This problem falls into the “Easy to Medium” difficulty range on LeetCode because while the concept is simple, identifying the optimal strategy requires understanding how to minimize the buying price while maximizing the selling price. It introduces the greedy algorithm approach, where at each step, we make a locally optimal choice hoping it leads to a globally optimal solution.
Imagine you’re at a candy store every day for a week, and each day the price of your favorite candy changes. You have a little bit of money, and you want to make the most extra money by buying the candy on a cheap day and selling it to your friend on a day when it’s more expensive. But you can only buy once and sell once, and you have to sell after you buy.
If you buy on Tuesday for 1 coin and sell on Friday for 6 coins, you make 5 coins of profit. That’s the best you can do! If the prices only went down every day, you’d make 0 profit because you wouldn’t sell at a loss. So, your job is to look at all the days, find the cheapest day to buy, and the most expensive day after that to sell, to make the most money.
Before we jump into the code, let’s clarify the key concepts this problem tests:
The idea is to iterate through the array once, maintaining two variables:
Let’s implement the solution in TypeScript. We’ll define the function with proper type annotations to ensure clarity and type safety, which is one of the benefits of using TypeScript over plain JavaScript.
function maxProfit(prices: number[]): number {
// If the array is empty or has only one element, no profit is possible
if (prices.length < 2) {
return 0;
}
// Initialize variables:
// minPrice is the lowest price seen so far (best time to buy)
// maxProfit is the maximum profit we can make
let minPrice: number = prices[0];
let maxProfit: number = 0;
// Iterate through the array starting from the second element
for (let i = 1; i < prices.length; i++) {
const currentPrice = prices[i];
// Update minPrice if the current price is lower
if (currentPrice < minPrice) {
minPrice = currentPrice;
}
// Update maxProfit if selling at current price gives a better profit
else {
const potentialProfit = currentPrice - minPrice;
maxProfit = Math.max(maxProfit, potentialProfit);
}
}
return maxProfit;
}
minPrice
as the first price in the array (the first possible
buying point) and maxProfit
as 0 (no profit yet).minPrice
, we update minPrice
because
buying cheaper is always better.minPrice
from the current price and update maxProfit
if this
profit is larger than the previous maximum.maxProfit
.Let’s test it with the example [7,1,5,3,6,4]
:
Let’s run a few test cases to verify our solution:
console.log(maxProfit([7, 1, 5, 3, 6, 4])); // Output: 5 (buy at 1, sell at 6)
console.log(maxProfit([7, 6, 4, 3, 1])); // Output: 0 (no profit possible)
console.log(maxProfit([1, 2])); // Output: 1 (buy at 1, sell at 2)
console.log(maxProfit([2])); // Output: 0 (can't sell)
As a bonus, let’s tackle a related problem often asked in interviews: Best Time to Buy and Sell Stock II. Here, you can buy and sell multiple times, as long as you sell before buying again. The goal is still to maximize profit.
[7,1,5,3,6,4]
.function maxProfitII(prices: number[]): number {
// If the array is empty or has only one element, no profit is possible
if (prices.length < 2) {
return 0;
}
// Initialize total profit
let totalProfit: number = 0;
// Iterate through the array
for (let i = 1; i < prices.length; i++) {
// If current price is higher than previous day's price,
// we can make a profit by buying yesterday and selling today
if (prices[i] > prices[i - 1]) {
totalProfit += prices[i] - prices[i - 1];
}
}
return totalProfit;
}
[7,1,5,3,6,4]
console.log(maxProfitII([7, 1, 5, 3, 6, 4])); // Output: 7
console.log(maxProfitII([1, 2, 3, 4, 5])); // Output: 4 (profit on each consecutive day)
console.log(maxProfitII([7, 6, 4, 3, 1])); // Output: 0 (no profit possible)
In this blog post, we’ve explored the Best Time to Buy and Sell Stock problem, a staple in technical interviews that tests array traversal and greedy algorithms. We started with an introduction to the problem, broke it down with an ELI5 analogy (buying and selling candy for profit), and implemented a solution in TypeScript with a time complexity of . We also tackled a bonus problem, Best Time to Buy and Sell Stock II, which allows multiple transactions and further reinforces the greedy approach.
Key takeaways:
number[]
for the input array) add
clarity and prevent runtime errors.These problems are excellent for practicing array manipulation and understanding how greedy algorithms can simplify seemingly complex tasks. As you prepare for Silicon Valley interviews, mastering such problems will boost your confidence in handling real-world optimization challenges. Stay tuned for the next post in our series, where we’ll dive into more medium-difficulty LeetCode problems with TypeScript!