| Difficulty | Easy | ||
|---|---|---|---|
| Source | 160 Days of Problem Solving | ||
| Tags |
|
The problem can be found at the following link: Problem Link
Given an array prices[] of length n, representing the prices of stocks on different days, find the maximum profit possible by buying and selling the stocks on different days, with at most one transaction allowed (1 buy + 1 sell). If no profit can be made, return 0.
Note: Stocks must be bought before being sold.
Input:
prices[] = [7, 10, 1, 3, 6, 9, 2]
Output:
8
Explanation:
Buy the stock on day 2 at price 1 and sell it on day 5 at price 9. Profit is 9 - 1 = 8.
Input:
prices[] = [7, 6, 4, 3, 1]
Output:
0
Explanation:
Prices decrease every day, so no profit is possible.
Input:
prices[] = [1, 3, 6, 9, 11]
Output:
10
Explanation:
Buy on day 1 (price = 1) and sell on the last day (price = 11). Profit is 11 - 1 = 10.
1 <= prices.size() <= 10^50 <= prices[i] <= 10^4
-
One Pass Solution:
- Maintain a
buyPriceto track the minimum price seen so far. - Track
maxProfitby comparing the current price's profit (currentPrice - buyPrice) to the previousmaxProfit. - Update
buyPricewhenever a lower price is encountered.
- Maintain a
-
Steps:
- Start by initializing
buyPriceas the first price andmaxProfitas 0. - Traverse the array and update
buyPriceandmaxProfitaccordingly. - The final
maxProfitgives the maximum possible profit with one transaction.
- Start by initializing
- Expected Time Complexity: O(n), where
nis the size of the array. Only one pass through the array is required. - Expected Auxiliary Space Complexity: O(1), as the solution uses a constant amount of additional space.
int maximumProfit(int prices[], int pricesSize) {
int buyPrice = prices[0];
int maxProfit = 0;
for (int i = 1; i < pricesSize; i++) {
if (prices[i] > buyPrice) {
maxProfit = (maxProfit > prices[i] - buyPrice) ? maxProfit : prices[i] - buyPrice;
} else {
buyPrice = prices[i];
}
}
return maxProfit;
}class Solution {
public:
int maximumProfit(vector<int> &prices) {
int buyPrice = prices[0], maxProfit = 0;
for (int i = 1; i < prices.size(); i++) {
if (prices[i] > buyPrice) {
maxProfit = max(maxProfit, prices[i] - buyPrice);
} else {
buyPrice = prices[i];
}
}
return maxProfit;
}
};class Solution {
public int maximumProfit(int prices[]) {
int buyPrice = prices[0], maxProfit = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] > buyPrice) {
maxProfit = Math.max(maxProfit, prices[i] - buyPrice);
} else {
buyPrice = prices[i];
}
}
return maxProfit;
}
}class Solution:
def maximumProfit(self, prices):
buyPrice = prices[0]
maxProfit = 0
for i in range(1, len(prices)):
if prices[i] > buyPrice:
maxProfit = max(maxProfit, prices[i] - buyPrice)
else:
buyPrice = prices[i]
return maxProfitFor discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β