Welcome to CodeYourCraft! Today, we're going to dive into a fascinating problem known as the Best Time to Buy and Sell Stock II. This problem is a classic in the world of Algorithms and Data Structures, and it's a great way to practice your problem-solving skills.
Let's get started! š
In this problem, you're given an array of n integers representing the stock prices on each day. You can buy and sell the stock multiple times, but there are no transaction fees. The goal is to maximize your profit by buying on days with low prices and selling on days with high prices.
Here's an example:
Prices = [7, 1, 5, 3, 6, 4]
Buy on day 1 (price = 1)
Sell on day 4 (price = 5)
Buy on day 5 (price = 3)
Sell on day 6 (price = 6)
Total profit = (5 - 1) + (6 - 3) = 8
In this example, we made two transactions, and the maximum profit we could have made is 8.
The problem can be solved by using a simple greedy approach. The idea is to keep track of the minimum price we've seen so far (min_price), and the profit we've made so far (total_profit). Whenever we encounter a price lower than min_price, we update min_price. And whenever we encounter a price greater than min_price, we add the difference between the current price and min_price to total_profit.
Here's a Python solution:
def maxProfit(prices):
if not prices:
return 0
min_price = float('inf')
total_profit = 0
for price in prices:
min_price = min(min_price, price)
total_profit += price - min_price
return total_profitIn the code above, we initialize min_price to a very large number (float('inf')) because we want to buy the stock at the lowest possible price. We then iterate through the prices, updating min_price and total_profit as needed.
Given the prices array `[2, 1, 3, 4, 5]`, what is the maximum profit that can be made by buying and selling the stock multiple times?
That's it for today! We hope you enjoyed learning about the Best Time to Buy and Sell Stock II. Stay tuned for more fascinating lessons on Data Structures and Algorithms here at CodeYourCraft. Happy coding! š