LeetCode Challenge: 121. Best Time to Buy and Sell Stock - JavaScript Solution 🚀
Rahul Kumar Barnwal

Rahul Kumar Barnwal @rahulgithubweb

About: Full-stack developer | Passionate about Problem Solving, Node.js, React, and Next.js | Tech mentor @ Polaris | Open Source Contributor | Sharing insights on coding, SaaS, and project building 🚀

Location:
Bangalore, Karnataka
Joined:
Apr 24, 2024

LeetCode Challenge: 121. Best Time to Buy and Sell Stock - JavaScript Solution 🚀

Publish Date: Dec 10 '24
11 1

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

Comments 1 total

  • Rahul Kumar Barnwal
    Rahul Kumar BarnwalDec 16, 2024

    Follow Me on GitHub 🚀

    If you found this solution helpful, check out more of my projects and solutions on my GitHub profile.

    Don't forget to follow for more updates!

Add comment