Use a min-heap to track all previous prices. When you see price , you have two choices: buy at or sell shares bought earlier.
If , you can profit by selling. Pop the smallest price from the heap (the buy price), add to profit. Then push twice: once as the sell price just used, once as a potential buy for the future. This "undoes" the sell if a better opportunity comes.