Stock Buy and Sell – Max one Transaction Allowed
JavaView on GFG
Time: O(n)
Space: O(1)
Advertisement
Intuition
Track minimum price seen so far. At each day, profit = price - min_so_far. Track maximum profit.
Algorithm
- 1min_price = prices[0], max_profit = 0.
- 2For each price: max_profit = max(max_profit, price - min_price). min_price = min(min_price, price).
Common Pitfalls
- •Must buy before selling. Update min_price at the end (or in same step since profit uses current price).
Stock Buy and Sell – Max one Transaction Allowed.java
Java
// Approach: Track minimum price seen so far; at each day, max profit = price - minPrice. Update max profit.
// Time: O(n) Space: O(1)
class Solution {
public int maximumProfit(int prices[]) {
int minSofar = prices[0];
int maxDiff = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] < minSofar) {
minSofar = prices[i];
}
maxDiff = Math.max(maxDiff, prices[i] - minSofar);
}
return maxDiff;
}
}
class Solution1 {
public int maxProfit(int[] prices) {
int n = prices.length;
int minPrice = prices[0];
int maxProfit = 0;
for (int i = 1; i < n; i++) {
minPrice = Math.min(prices[i], minPrice);
int profit = prices[i] - minPrice;
maxProfit = Math.max(profit, maxProfit);
}
return maxProfit;
}
}Advertisement
Was this solution helpful?