This is a solution implemented in Python. Let's consider 'trades' as a list containing stock prices. def calculate_profit ( trades ) : buy = sell = trades [ 0 ] pairs = [ ] profit = 0 for i in range ( 1 , len ( trades ) ) : if trades [ i ] < sell : pairs . append ( ( buy , sell ) ) profit += sell - buy buy = sell = trades [ i ] else : sell = trades [ i ] pairs . append ( ( buy , sell ) ) profit += sell - buy return pairs , profit The code above goes through the list of trades. For each trade, if the current price is lower than the selling price, it adds the buy/sell pair to the pairs list and updates the total profit, as well as the buy and sell prices. If not, it simply updates the sell price. Finally, it appends the last pair and includes the profit earned from that transaction.