DEV Community

Giuseppe
Giuseppe

Posted on

LeetCode #121. Best Time to Buy and Sell Stock

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; } } 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)