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 β€’ Edited on

3 2 2 2 2

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

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (1)

Collapse
 
rahulgithubweb profile image
Rahul Kumar Barnwal β€’

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!

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

AWS Security LIVE!

Hosted by security experts, AWS Security LIVE! showcases AWS Partners tackling real-world security challenges. Join live and get your security questions answered.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❀️