121. Best Time to Buy and Sell Stock
Solution
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
let l = 0;
let r = 1;
let maxProfit = 0;
while(r < prices.length) {
if (prices[l] < prices[r]) {
// Profitable transaction
const profit = prices[r] - prices[l];
maxProfit = Math.max(maxProfit, profit);
} else {
// Not Profitable transaction
l = r;
}
r++;
}
return maxProfit;
};
Complexity
- Time Complexity: O(N), where N is the size of
prices
. - Space Complexity: O(1), we are not using extra memory.