DEV Community

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

Posted on

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

Top Interview 150

This problem is a classic extension of the stock profit challenge. You can make multiple transactions to maximize your profit, buying and selling as many times as you likeβ€”just not holding more than one stock at a time. Let’s break it down and solve LeetCode: Best Time to Buy and Sell Stock II with an efficient approach.


πŸš€ Problem Description

You are given an array prices, where prices[i] is the price of a stock on the ith day.
Find and return the maximum profit you can achieve by making as many transactions as needed.

  • You can buy and sell on the same day.
  • You can only hold one share at a time.

πŸ’‘ Examples
Example 1

Input: prices = [7,1,5,3,6,4]  
Output: 7  
Explanation: Buy on day 2 (price = 1), sell on day 3 (price = 5), profit = 4.
Then buy on day 4 (price = 3), sell on day 5 (price = 6), profit = 3.  
Total profit = 4 + 3 = 7.
Enter fullscreen mode Exit fullscreen mode

Example 2

Input: prices = [1,2,3,4,5]  
Output: 4  
Explanation: Buy on day 1 (price = 1), sell on day 5 (price = 5), profit = 4.

Enter fullscreen mode Exit fullscreen mode

Example 3

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: No profitable transactions can be made.
Enter fullscreen mode Exit fullscreen mode

πŸ† JavaScript Solution

The key to solving this problem is to take advantage of every upward slope in the price array. Whenever the price increases, sell for a profit.

Greedy Approach

var maxProfit = function(prices) {
    let maxProfit = 0;

    for (let i = 1; i < prices.length; i++) {
        if (prices[i] > prices[i - 1]) {
            maxProfit += prices[i] - prices[i - 1];
        }
    }

    return maxProfit;
};
Enter fullscreen mode Exit fullscreen mode

πŸ” How It Works

  1. Iterate through the prices: Start from the second day and compare the price with the previous day.
  2. Add profit for increases: If today’s price is higher than yesterday’s, add the difference to maxProfit.
  3. Ignore declines: Skip over days where prices drop or remain the same.

πŸ”‘ Complexity Analysis

  • > Time Complexity: O(n), where n is the number of days. We traverse the array once.
  • > Space Complexity: O(1), as no extra memory is used.

πŸ“‹ Dry Run

Input: prices = [7,1,5,3,6,4]

Leetcode

Output: 7


✨ Pro Tips for Interviews

  1. Understand the strategy: Explain how greedily capturing every upward slope guarantees the maximum profit.
  2. Clarify constraints: Confirm with the interviewer that multiple transactions are allowed.
  3. Edge cases:
    • Single-day input.
    • Constant prices (e.g., [3,3,3]).
    • Decreasing prices (e.g., [5,4,3,2,1]).

πŸ“š Learn More

Check out the full explanation and code walkthrough on my Dev.to post:
πŸ‘‰ Best Time to Buy and Sell Stock - JavaScript Solution

What’s your approach to this problem? Let’s discuss below! πŸš€

JavaScript #LeetCode #CodingInterview #ProblemSolving

Top comments (0)