Learner Level
Implement the maximumProfitSingleTransaction method that returns the best stock profit using at most one buy and one sell.
The input contains an array prices and its length size. Each value represents the stock price on that day.
Your task is to return the maximum profit possible by buying once and selling once later. You must buy before you sell. If no profitable transaction is possible, return 0.
Scan the prices from left to right while keeping the lowest buying price seen so far.
For each day, treat that day as a possible selling day. The profit is the current price minus the lowest earlier price. Update the best profit whenever this value is larger.
If prices keep decreasing, the best profit remains 0 because it is better not to make a transaction.
Pseudocode:
function maximumProfitSingleTransaction(prices, size):
if size == 0:
return 0
minPrice = prices[0]
bestProfit = 0
for i from 1 to size - 1:
profit = prices[i] - minPrice
bestProfit = max(bestProfit, profit)
minPrice = min(minPrice, prices[i])
return bestProfit