Problem · Dynamic Programming

Count Bounded Share Transactions

Learn this problem
MediumOptiver logoOptiverFULLTIMEOA

Problem statement

You start with startShares shares. One transaction does exactly one of the following:

  • buy one share, increasing the holding by one; or
  • sell one share, decreasing the holding by one, provided the holding is positive before the sale.

Count all distinct transaction sequences whose length is between 0 and maxTransactions, inclusive, and that finish with exactly targetShares shares. The empty sequence counts when the starting and target holdings are equal.

Return the total number of valid sequences.

Function

countTransactionSequences(startShares: int, targetShares: int, maxTransactions: int) → long

Examples

Example 1

startShares = 1targetShares = 2maxTransactions = 3return = 4

One one-transaction sequence and three three-transaction sequences finish at two shares: B, BBS, BSB, and SBB.

Example 2

startShares = 0targetShares = 0maxTransactions = 2return = 2

The empty sequence and BS are valid. A sequence cannot begin with a sale at zero shares.

Constraints

  • 0 <= startShares <= 60
  • 0 <= targetShares <= 60
  • 0 <= maxTransactions <= 60
  • The answer fits in a signed 64-bit integer.

More Optiver problems

drafts saved locally
public long countTransactionSequences(int startShares, int targetShares, int maxTransactions) {
    // write your code here
}
startShares1
targetShares2
maxTransactions3
expected4
checking account