FastPrepCalculate Net Profit

Calculate Net Profit

JP Morgan Chase logoJP Morgan Chase● EasyOA
Learn

Problem statement

A quantitative trading firm aims to develop a tool to track the net profit/loss of the firm at any point in time. This tool processes a list of events, where each event falls into one of four categories:

  • BUY stock quantity: Indicates the purchase of quantity shares of stock at the market price.
  • SELL stock quantity: Indicates the sale of quantity shares of stock at the market price.
  • CHANGE stock price: Indicates a change in the market price of stock by price amount, which can be positive or negative.
  • QUERY: Requests the net profit/loss from the start of trading until the current time.

The tool should return a list of numbers corresponding to each QUERY event.

Function

calculateNetProfit(events: String[]) → long[]

Complete the function calculateNetProfit in the editor.

calculateNetProfit has the following parameter:

  1. String[] events: an array of strings describing the events

Returns long[]: the answers to the "QUERY" events

My deepest, sincere, and boundless gratitude to an amazing friend for all their help. 🩵

Examples

Example 1

events = ["BUY googl 20", "BUY aapl 50", "CHANGE googl 6", "QUERY", "SELL aapl 10", "CHANGE aapl -2", "QUERY"]return = [120, 40]

The 20 shares of googl gain 6 each, so the first query returns 120. Selling 10 shares of aapl leaves 40 shares. When aapl's price then falls by 2, the portfolio loses 80, so the second query returns 40.

Constraints

  • 1 ≤ events.length ≤ 10^5
  • 1 ≤ events[i].length ≤ 21
  • For every SELL stock quantity event, it is guaranteed that enough shares are owned.
  • 1 ≤ quantity ≤ 10^3
  • The absolute value of a change in the price of any stock at any event will not exceed 10³.

More JP Morgan Chase problems

See JP Morgan Chase hiring insights
public long[] calculateNetProfit(String[] events) {
  // write your code here
}
events["BUY googl 20", "BUY aapl 50", "CHANGE googl 6", "QUERY", "SELL aapl 10", "CHANGE aapl -2", "QUERY"]
expected[120, 40]
Checking account…