DEV Community

Cover image for LeetCode Challenge: 121. Best Time to Buy and Sell Stock - JavaScript Solution πŸš€
Rahul Kumar Barnwal
Rahul Kumar Barnwal

Posted on

LeetCode Challenge: 121. Best Time to Buy and Sell Stock - JavaScript Solution πŸš€

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.
Enter fullscreen mode Exit fullscreen mode

Example 2

Input: prices = [7,6,4,3,1]  
Output: 0  
Explanation: No profit can be made as prices decrease every day.
Enter fullscreen mode Exit fullscreen mode

πŸ† 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;
};
Enter fullscreen mode Exit fullscreen mode

πŸ” How It Works

  1. Track the Minimum Price:
    • As you iterate, keep track of the smallest price encountered so far.
  2. Calculate Potential Profit:
    • For each price, calculate the profit as the difference between the current price and the minimum price.
  3. 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]
Max Profit
Output: 5


✨ Pro Tips for Interviews

  1. Clarify assumptions: Ensure the interviewer confirms there’s always at least one price in the input.
  2. Handle edge cases: Single-day input (prices.length = 1). Constant or decreasing prices ([7,6,5,4,3]).
  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! πŸš€

JavaScript #LeetCode #CodingInterview #ProblemSolving

Top comments (0)