To maximize profit, we need to buy at the lowest price and sell at the highest price after the
buy. We
initialize
the
buy price
with the first element
of the array and
iterate
through
the array. If the current price is
higher
than the buy price, we
calculate
the profit and
update
the global profit if this
profit is greater. If the current price is
lower
than the buy price, we
update
the buy price to the current
price.
class Solution { public int maxProfit(int[] prices) { int globalProfit = 0; int buy = prices[0]; for(int i=1;i<prices.length;i++){ int sell = prices[i]; if(sell > buy){ int profit = sell - buy; globalProfit = Math.max(profit,globalProfit); } else{ buy = sell; } } return globalProfit; } }
The algorithm iterates through the array once, making it linear in time complexity.
The algorithm uses a constant amount of extra space, regardless of the input size.