Prepin
Log in

Go through a list of trades and generate a list of buy/sell pairs along with the total profit from the trades.

Approach / Explanation

This question presents a list of trades for which you need to return pairs of buy/sell transactions and calculate the total profit. The trades are represented by a series of numbers, each indicating the price of a specific stock at different times. Your task is to identify pairs of numbers where the first number (the 'buy' price) is less than the second number (the 'sell' price) to maximize profit. Essentially, you need to locate the local minima (buy points) and local maxima (sell points). There are several key considerations to keep in mind while addressing this question: The buy/sell pairs must be arranged in chronological order; you cannot sell a stock before you buy it. In a scenario where the stock price is consistently declining, no trades should take place as this would result in a loss. If multiple trading cycles are possible, the total profit should be calculated as the sum of profits from each cycle.

Suggested Answer

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.

Alternative Answer

This example presents a different method utilizing JavaScript. Let’s consider 'prices' as an array containing stock prices.

Question Details

Difficulty & Category

Medium
algorithms

Companies

Robinhood

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.