Stock Buy and Sell
- Shreyas Naphad
- Jun 5, 2024
- 1 min read
In this article, we will solve the problem of determining the maximum profit that we can get from buying and selling a single stock given an array of stock prices.
Example:
Input: [12, 1, 0, 2, 6, 4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. We cannot buy on day 2 and selling on day 1 is not allowed because we must buy before we sell.
Solution:
To solve this problem, we will keep track of the minimum price found so far and calculate the potential profit at every step. This approach ensures that we find the maximum possible profit.
Steps to Solve:
1. Initialize Variables:
o Initialize minPrice to a very high value such as INT_MAX to keep track of the lowest price.
o Initialize maxProfit to 0 to keep track of the maximum profit.
2. Iterate Through Prices:
o For each price in the array, update minPrice if the current price is lower than minPrice.
o Calculate the potential profit by subtracting minPrice from the current price.
o Update maxProfit if the potential profit is higher than the current maxProfit.
3. Return Result:
o After iterating through the prices, return maxProfit as the result.
Time Complexity: O(N)
Space Complexity: O(1)
Kommentare