Time Complexity: O(n) - single pass through array
Space Complexity: O(1) - only using constant extra variables, no additional space used
class Solution {
public int maxProfit(int[] prices) {
int maxProfit = 0;
int lowStockDay = prices[0];
for (int i = 1; i < prices.length; i++) {
if (prices[i] < lowStockDay)
lowStockDay = prices[i];
int profit = prices[i] - lowStockDay;
if(maxProfit < profit)
maxProfit = profit;
}
return maxProfit;
}
}
Top comments (0)