Problem · Array

Generate an Optimal Portfolio Trading Report

Learn this problem
MediumPoint72 logoPoint72PHONE SCREEN

Problem statement

Given an array prices, where prices[i] is the price of one stock on day i, generate a report for an optimal sequence of buy-and-sell transactions.

You may complete as many transactions as you like, but you may hold at most one share at a time. A new share may be bought only after the previous share has been sold. Each reported transaction must have positive profit.

For this exercise, assume the transaction list is canonicalized into maximal rising runs. Skip days while the next price is less than or equal to the current price; the resulting day is the buy day. Then continue while the next price is greater than or equal to the current price; the final day of that run is the sell day. Report the transaction only when its sell price is greater than its buy price.

Return one String for each transaction, followed by one total line. A transaction line has exactly the form BUY <buyDay> <buyPrice> SELL <sellDay> <sellPrice> PROFIT <profit>. The final line has exactly the form TOTAL PROFIT <totalProfit>. Day indices are zero-based. If no profitable transaction exists, return only TOTAL PROFIT 0.

Function

portfolioTradingReport(prices: int[]) → String[]

Examples

Example 1

prices = [7,1,5,3,6,4]return = ["BUY 1 1 SELL 2 5 PROFIT 4","BUY 3 3 SELL 4 6 PROFIT 3","TOTAL PROFIT 7"]

The maximal rising runs are from day 1 at price 1 to day 2 at price 5, and from day 3 at price 3 to day 4 at price 6. Their profits are 4 and 3, for a total profit of 7.

Example 2

prices = [1,2,2,4]return = ["BUY 0 1 SELL 3 4 PROFIT 3","TOTAL PROFIT 3"]

The equal prices on days 1 and 2 remain inside one maximal rising run. Buying on day 0 and selling on day 3 earns 3.

Example 3

prices = []return = ["TOTAL PROFIT 0"]

There are no days on which to trade, so the report contains only the zero-profit total line.

Constraints

  • 0 <= prices.length <= 30000.
  • 0 <= prices[i] <= 10000.
  • The input passed to the judged function satisfies these bounds; the source-described validation decorator therefore does not need to report invalid input through this return value.

More Point72 problems

drafts saved locally
public String[] portfolioTradingReport(int[] prices) {
  // write your code here
}
prices[7,1,5,3,6,4]
expected["BUY 1 1 SELL 2 5 PROFIT 4", "BUY 3 3 SELL 4 6 PROFIT 3", "TOTAL PROFIT 7"]
checking account