Problem · Array

Capital Gains Tax from Trades

Learn this problem
MediumArcesium logoArcesiumINTERNFULLTIMEOA

Problem statement

Process chronological stock trades and calculate the tax on realized profit. Each trade is a comma-separated string:

date,ticker,side,shares,price
  • side is B for a buy or S for a sell.
  • shares is a positive integer.
  • price is a non-negative decimal amount with at most two digits after the decimal point.

Track positions separately by ticker and match closing shares against open lots in first-in, first-out order. A sell closes long shares before opening a short position; a buy closes short shares before opening a long position. A single trade may close an existing position and open the opposite position with its remaining shares.

For a closed long share, realized profit is sell price - buy price. For a closed short share, realized profit is short-sale price - cover price. Open lots do not contribute realized profit.

Add realized profit across every ticker. Tax is 25% of the positive total; when the total is zero or negative, tax is zero. Return the tax as US currency with a leading $, comma separators, and exactly two decimal places.

Function

calculateTax(trades: String[]) → String

Examples

Example 1

trades = ["2024-01-01,ABC,B,10,100.00","2024-01-02,ABC,S,4,120.00"]return = "$20.00"

Selling four shares realizes 4 * (120 - 100) = $80. Tax is 25%, or $20.00.

Example 2

trades = ["2024-01-01,ABC,S,5,50.00","2024-01-02,ABC,B,5,60.00"]return = "$0.00"

Covering the short realizes a loss of 5 * (50 - 60) = -$50, so the tax is zero.

Constraints

  • trades.length >= 1.
  • Trades are ordered chronologically.
  • Every trade uses the five-field format described above.
  • Every testcase produces a tax amount that is an exact number of cents.

More Arcesium problems

drafts saved locally
public String calculateTax(String[] trades) {
  // Write your code here.
}
trades["2024-01-01,ABC,B,10,100.00","2024-01-02,ABC,S,4,120.00"]
expected"$20.00"
checking account