FastPrepRealized PnL with Oldest Inventory First

Realized PnL with Oldest Inventory First

Belvedere Trading logoBelvedere Trading● MediumFULLTIMEOA
Learn

Problem statement

A trading desk processes a day's trades in order. Trade i is described by side[i], quantity[i], and price[i].

  • side[i] = 1 is a buy. It appends quantity[i] shares to inventory at unit cost price[i].
  • side[i] = 0 is a sell. It removes shares from the oldest remaining buy lots first.

For each sold share, realized profit or loss is the sale price minus that share's matched purchase price. Return the running total realized profit or loss after every trade.

Function

realisedPnl(side: int[], quantity: int[], price: int[]) → long[]

Examples

Example 1

side = [1,1,0]quantity = [10,5,12]price = [100,120,130]return = [0,0,320]

The first two trades add inventory. The sell matches 10 shares bought at 100 and 2 shares bought at 120, realizing 10 * 30 + 2 * 10 = 320.

Example 2

side = [1,0]quantity = [5,5]price = [20,15]return = [0,-25]

Selling all five shares at 15 after buying them at 20 realizes 5 * (15 - 20) = -25.

Constraints

  • 1 <= side.length <= 10^5.
  • side.length = quantity.length = price.length.
  • side[i] is either 0 or 1.
  • 1 <= quantity[i], price[i] <= 10^9.
  • At every sell, inventory contains at least quantity[i] shares.
  • Every returned running total fits in a signed 64-bit integer.
  • Every matched-lot profit or loss and every intermediate realized-PnL running total fits in a signed 64-bit integer.

More Belvedere Trading problems

See Belvedere Trading hiring insights
public long[] realisedPnl(int[] side, int[] quantity, int[] price) {
  // write your code here
}
side[1,1,0]
quantity[10,5,12]
price[100,120,130]
expected[0,0,320]
Checking account…