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.
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.
Example 3
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: No profitable transactions can be made.
π 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;
};
π How It Works
- Iterate through the prices: Start from the second day and compare the price with the previous day.
- Add profit for increases: If todayβs price is higher than yesterdayβs, add the difference to
maxProfit
. - 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]
Output: 7
β¨ Pro Tips for Interviews
- Understand the strategy: Explain how greedily capturing every upward slope guarantees the maximum profit.
- Clarify constraints: Confirm with the interviewer that multiple transactions are allowed.
- 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! π
Top comments (0)