121. Best Time to Buy and Sell Stock
Last updated
Last updated
/**
* Time complexity : O(N)
* Space complexity : O(1)
*/
class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length < 2) return 0;
int maxProfit = 0;
int minStockSoFar = prices[0];
for(int i = 1; i < prices.length; i++) {
minStockSoFar = Math.min(minStockSoFar, prices[i]);
maxProfit = Math.max(maxProfit, prices[i]-minStockSoFar);
}
return maxProfit;
}
}