Welcome to CodeYourCraft! Today, we'll dive into the exciting world of Data Structures and Algorithms, and specifically focus on a problem called "Best Time to Buy and Sell Stock I". This problem is a classic in the algorithmic world and is very relevant for real-world applications. Let's get started! š
Imagine you are given an array of stock prices for a single stock over a certain time period. Your task is to determine the maximum profit you could have made if you bought one share of the stock at the lowest price and sold it at the highest price.
Let's break it down with a practical example.
# Example prices for a stock
prices = [7, 1, 5, 9, 6, 1, 8, 4, 7]In this example, the lowest price is 1, and the highest price is 9. The difference between them is 8, which is the maximum profit you could have made by buying the stock at the lowest price and selling it at the highest price.
To solve this problem, we can use a simple approach called "Keep Track of the Minimum Price Encountered So Far". Here's how it works:
Initialize two variables: minPrice and maxProfit. Set minPrice to the first price in the array, and set maxProfit to 0.
Iterate through the array. For each price, check if it is greater than minPrice. If it is, update maxProfit by subtracting minPrice from the current price and adding the difference to maxProfit. Update minPrice with the current price if it is less than the current minPrice.
After iterating through the entire array, maxProfit will hold the maximum profit you could have made.
Here's how the code would look like:
def maxProfit(prices):
minPrice = prices[0]
maxProfit = 0
for price in prices:
if price < minPrice:
minPrice = price
elif price > minPrice:
maxProfit += price - minPrice
minPrice = price
return maxProfit
# Test the function
prices = [7, 1, 5, 9, 6, 1, 8, 4, 7]
print(maxProfit(prices)) # Output: 8What is the maximum profit you could have made if you bought one share of the stock at the lowest price and sold it at the highest price in the given prices array?
And there you have it! You've now learned how to solve the "Best Time to Buy and Sell Stock I" problem. As you practice more, you'll find that understanding these problems is key to mastering Data Structures and Algorithms. Happy coding! š
Remember, CodeYourCraft is here to help you every step of the way. If you have any questions or need further clarification, feel free to reach out! š”