What will be helpful is finding a maximum difference so far (which is the profit) and the maximum price starting from the right. If we know the maximum price starting from the end, we can calculate the difference between that, and each subsequent element moving leftwards.
What this does is ensure that we're accounting for the order of the prices. With each step towards the front of the array, we can find a new maximum profit (maxProfit
) based on the new current max price (curMax
) that we encounter using something like the below logic:
1if (temp > curMax) {
2 curMax = temp;
3}