Problem
You are given an integer array prices, where prices[i] represents the stock price on the ith day. Choose one day to buy a stock and a different future day to sell it to maximize your profit.Return the maximum profit that can be achieved. If you cannot achieve any profit, return 0.
Example
Consider the following example to understand the expected input and output.Input
prices = [7,1,5,3,6,4]
Output
5
Solution
The key idea is to traverse the array from left to right while keeping track of the lowest buying price seen so far.The variable buy stores the lowest stock price at which we could have bought the stock before the current day.
For every new price, if the current price is greater than buy, we can sell the stock and calculate the profit as prices[i] - buy. The maximum profit is updated whenever a higher profit is found.
If the current price is lower than or equal to buy, we update buy because buying at this lower price can potentially produce a higher profit on a future day.
This approach ensures that the stock is always bought before it is sold because buy only represents a price encountered at an earlier position in the array.
public int maxProfit(int[] prices) {
// Handle null or empty input.
if (prices == null || prices.length == 0) {
return 0;
}
int max = 0;
int buy = prices[0];
for (int i = 1; i < prices.length; i++) {
if (prices[i] > buy) {
// Calculate profit by selling at the current price.
max = Math.max(max, prices[i] - buy);
} else {
// Update the lowest buying price.
buy = prices[i];
}
}
return max;
}
Complexity
The array is traversed only once, and each element is processed exactly once. Therefore, the time complexity is O(n).The algorithm uses only two variables, buy and max, apart from the input array. Therefore, the extra space complexity is O(1).
Comments
No comments yet. Ask a question or share what helped.